2013-06-04 161 views
2

我基本上想要播放一系列的mp3文件。 它不应该很难,但我努力保持解码器和扬声器通道打开,以便在播放一首歌后播放新的mp3数据。 下面是我迄今为止播放一个mp3文件的精简版。Node.js音频播放器

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(用于解码)和node-speaker(用于音频输出通过扬声器)。

回答

2

没有任何关于您提到的模块的经验,但我认为您需要在每次播放歌曲时重新打开扬声器(因为您将解码后的音频输入到它,解码器完成后它将被关闭) 。你可以将你的代码改写成这样(未经测试);

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

另一种解决方案(其中一个我宁愿)是使用非常漂亮的async模块:

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

酷......工作真棒! –