Node.jsaudio播放器

我基本上想要一个接一个地播放一系列的mp3文件。 它不应该很难,但我努力保持解码器和扬声器通道打开后,播放一首歌曲后,新的MP3数据。 这里是我迄今为止的一个精简版,播放一个mp3文件。

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 }); 

我正在使用TooTallNate的模块node-lame (用于解码)和节点扬声器 (用于通过扬声器输出audio)。

没有任何关于你提到的模块的经验,但是我认为每次你想播放一首歌曲时你都需要重新打开扬声器(因为你把解码后的audioinput到它,解码器完成后它将被closures)。

你可以重写你的代码,像这样(未经testing);

 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); 

另一个解决scheme(我更喜欢)是使用非常好的asynchronous模块:

 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(); }); });