I m trying to make a TV from a raspberry pi, in javascript, the type who play the same playlist again and again. Playing the files aren t a problem, but I m stuck at the asynchronous part of javascript Here the code wich bother me:
function play (file)
{
exec('home/pi/play.sh', [file], function (error, stdout, stderr){
if (PIndice != Playlist.length-1){
PIndice=PIndice+1;
}else{
PIndice=0;
}
play(Playlist[PIndice]);
});
Another function call it with Playlist[0] when I m sure there s a pathname in it.
My question is: Is it safe? Isn t recursion will end up killing the cpu? I ve though about using setTimeOut but I didn t found any way to get the duration of the video.
I ve tried calling play in a loop, but I just succeed at playing the whole playlist in the same time.
I don t ask for a all-made solution, just hint to where I can find a way to do it properly Is there a way to wait for play to end before calling it again, even if javascript is asynchronous?
EDIT: All files are in MPEG4, Playlist is just a array of string, wich contain the pathname of the video file to play. It s supposed to play without internet, so there s no browser, and I can t use html request to have the metadata of the video to get it duration.
EDIT2: I forgot to tell that play.sh just start the player if there s no other instance of it, it is just a remain of the previous version where I didn t know about the callback of execFile
That's not actually a recursive call and won't cause a problem with stack depth. Notice that the play method is called within a callback, and not from within the play method itself.
That being said, the exec callback is called once the child process terminates. Since play.sh just starts the player, it sounds like it will terminate before the file is done being played which means that play will be called multiple times before the first track completes. The code as you have it would work best if you're exec will call something that runs for the duration of the track, and then terminates. That should correctly set you up to play the next track after each one completes.
If for some reason you cannot keep the process running until the track is complete, you will have to design the play.sh file to be able to be called multiple times and return the status of the current track. Something like:
function play (file)
{
exec('home/pi/play.sh', [file], function (error, stdout, stderr){
if(stdout == 'done') {
if (PIndice != Playlist.length-1){
PIndice=PIndice+1;
} else {
PIndice = 0;
}
}
play(Playlist[PIndice]);
});
};
That way the PIndice is only incremented once the file is done playing, and then it can start the next track.