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

4

1 回答 1

3

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();
  });
});
于 2013-06-04T21:12:00.057 回答