Node.js音频播放器

Node.js audio player

本文关键字:播放器 音频 js Node      更新时间:2023-09-26

我基本上想一个接一个地播放一系列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(用于通过扬声器输出音频)。

没有任何经验与你提到的模块,但我认为你需要重新打开扬声器每次你想播放一首歌(因为你管道解码音频到它,它将关闭一旦解码器完成)。

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

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