I'm playing around with events triggering sounds (500 msec long), therefore I use the lame
library.
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);
}
}
Is there any way to preload the stream/file, so I won't need to load it on every single event? it actually blocks my whole while loop and making it async didn't work. How can I reduce latency and make it more efficient?
You can cache the mp3 file to a buffer
, then convert that buffer
to a readable stream when you need.
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;
}