Node.js音频播放器

6

我基本上想要播放一系列的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(用于解码)和node-speaker(用于通过扬声器输出音频)。
1个回答

3

我完全没有使用你提到的模块的经验,但是我认为每次想播放一首歌曲时,您需要重新打开扬声器(因为您将解码后的音频传输到它,一旦解码器完成,它就会关闭)。

您可以重写您的代码,类似于以下内容(未经测试):

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接