shime / play-sound

Play sounds by shelling out to one of the available audio players.
MIT License
207 stars 31 forks source link

Wait till the current file has been played till the end and then play the next audio file #37

Open komms opened 5 years ago

komms commented 5 years ago

Does play-sound provide an option to know whether the player is running or not? As my function is runing at 3 times per second, if there are two audio files to be played then the second audio file breaks the player playing the first audio file and then plays the second file.

Is there a way to let the player play till the end of the current audio file and then play the next file in the queue?

MARCoTheRobot commented 1 year ago

Doesn't look like this has gotten a lot of activity in the past 4 years, but in case anyone is still wondering the way I was, this is how I approached it.

As per the readme, you can access the child process of the player itself:

// access the node child_process in case you need to kill it on demand
var audio = player.play('foo.mp3', function(err){
  if (err && !err.killed) throw err
})

When a Node process ends, it fires an 'exit' event as per the official documentation.

If you add an event listener to that, you can chain as many sequential audio files to play as you would like in a queue using something similar to the sample below, provided that you re-add that exit handler each time.

const audioFiles = [ 
                                   "first_audio.wav",
                                   "second_audio.wav",
                                   "third_audio.wav",
                                    ...
                                    "last_audio.wav"
                         ];

var audioIndex = 0;

var audio = player.play(audioFiles[audioIndex], function(err){
  if (err && !err.killed) throw err
});

const exitLoop = async (code) => {
         if(audioIndex < audioFiles.length){
               audioIndex++;
               audio = player.play(audioFiles[audioIndex], function(err){
  if (err && !err.killed) throw err
});

//Re-add the 'exit' handling function each time because otherwise it will not iterate after the first process exits.
audio.on('exit',exitLoop);
       }
      else{
        //It finished the sequence, so do whatever you want - set the process to null, loop audioFiles by setting index to zero and trying again, etc.
    }
}

//Add the exitLoop function for the first process
audio.on('exit',exitLoop);