Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js audio player

I basically want to play a series of mp3-files after each other. It shouldn't be to hard, but I'm struggling to keep the decoder and speaker channel open to feed new mp3 data in after a song has been played. Here is a condensed version from what I have so far, playing one mp3 file.

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

I'm using TooTallNate's modules node-lame (for decoding) and node-speaker (for audio output through the speakers).

like image 613
johnny Avatar asked Jun 04 '13 21:06

johnny


1 Answers

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();
  });
});
like image 123
robertklep Avatar answered Oct 31 '22 22:10

robertklep