0

我正在玩触发声音的事件(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);
    }
}

有没有办法预加载流/文件,所以我不需要在每个事件上加载它?它实际上阻止了我的整个 while 循环并使其异步不起作用。如何减少延迟并提高效率?

4

1 回答 1

2

您可以将 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;
}
于 2017-10-29T07:01:26.773 回答