fs.createReadStream('b.mp3') 减少延迟

fs.createReadStream('b.mp3') reduce latency

我正在研究触发声音的事件(500 毫秒长),因此我使用 lame 库。

var lame = require('lame');
var fs = require('fs');
var Speaker = require('speaker');

while(listening) {
    if(eventIsFired) {
        fs.createReadStream('b.mp3')
            .pipe(new lame.Decoder)
            .pipe(new Speaker);
    }
}

有什么方法可以预加载 stream/file,这样我就不需要在每个事件上都加载它了吗?它实际上阻塞了我的整个 while 循环并使其异步不起作用。如何减少延迟并提高效率?

您可以将 mp3 文件缓存到 buffer,然后在需要时将其 buffer 转换为可读流。

var lame = require('lame');
var fs = require('fs');
var Speaker = require('speaker');
var Readable = require('stream').Readable;

var mp3Buffer = fs.readFileSync('b.mp3');

while(listening) {
    if(eventIsFired) {
        bufferToReadableStream(mp3Buffer)
            .pipe(new lame.Decoder)
            .pipe(new Speaker);
    }
}

function bufferToReadableStream(buffer) {
    let stream = new Readable();
    stream.push(buffer);
    stream.push(null);
    return stream;
}