I basically want to play a series of mp3-files after each other. It shouldn't be to hard, but I'm struggling to keep the decoder and speaker channel open to feed new mp3 data in after a song has been played. Here is a condensed version from what I have so far, playing one mp3 file.
var audioOptions = {channels: 2, bitDepth: 16, sampleRate: 44100};
// Create Decoder and Speaker
var decoder = lame.Decoder();
var speaker = new Speaker(audioOptions);
// My Playlist
var songs = ['samples/Piano11.mp3','samples/Piano12.mp3','samples/Piano13.mp3'];
// Read the first file
var inputStream = fs.createReadStream(songs[0]);
// Pipe the read data into the decoder and then out to the speakers
inputStream.pipe(decoder).pipe(speaker);
speaker.on('flush', function(){
// Play next song
});
I'm using TooTallNate's modules node-lame (for decoding) and node-speaker (for audio output through the speakers).
No experience whatsoever with the modules you mention, but I think you need to reopen the speaker each time you want to play a song (since you pipe the decoded audio to it, it will be closed once the decoder is done).
You could rewrite your code to something like this (untested);
var audioOptions = {channels: 2, bitDepth: 16, sampleRate: 44100};
// Create Decoder and Speaker
var decoder = lame.Decoder();
// My Playlist
var songs = ['samples/Piano11.mp3','samples/Piano12.mp3','samples/Piano13.mp3'];
// Recursive function that plays song with index 'i'.
function playSong(i) {
var speaker = new Speaker(audioOptions);
// Read the first file
var inputStream = fs.createReadStream(songs[i]);
// Pipe the read data into the decoder and then out to the speakers
inputStream.pipe(decoder).pipe(speaker);
speaker.on('flush', function(){
// Play next song, if there is one.
if (i < songs.length - 1)
playSong(i + 1);
});
}
// Start with the first song.
playSong(0);
Another solution (one which I would prefer) is to use the very nice async module:
var async = require('async');
...
async.eachSeries(songs, function(song, done) {
var speaker = new Speaker(audioOptions);
var inputStream = fs.createReadStream(song);
inputStream.pipe(decoder).pipe(speaker);
speaker.on('flush', function() {
// signal async that it should process the next song in the array
done();
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With