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

时间:2017-10-28 20:55:12

标签: node.js latency lame nodejs-stream

我正在玩触发声音的事件(500毫秒长),因此我使用var slides = document.getElementsByClassName('slider'); [].forEach.call(slides, function (s) { var next = s.getElementsByClassName('next')[0], prev = s.getElementsByClassName('prev')[0], inner = s.getElementsByClassName('inner')[0], slides = inner.getElementsByClassName('slide'), currentTeamIndex = 0, width = 1344; var $gameList = $('#gameList'), $gameContainer = $gameList.find('.slides'), $game = $gameContainer.find('.slide'); function switchSlide() { inner.style.left = -width * currentTeamIndex + 'px'; } next.addEventListener('click', function () { currentTeamIndex++; if (currentTeamIndex >= slides.length) { currentTeamIndex = 0; } switchSlide(); }); prev.addEventListener('click', function () { currentTeamIndex--; if (currentTeamIndex < 0) { currentTeamIndex = slides.length - 1; } switchSlide(); }); }); 库。

lame

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

1 个答案:

答案 0 :(得分: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;
}