javascripthtmlhtml5-audio

How to autoplay an audio even when the page is not active


Have a list, in which the names of the songs I want to play are placed in an order...when I have to play the next one, my function gets the currently playing song's index, and plays the next one in the list.

toPlay = autoPlayOrder[(autoPlayOrder.indexOf(playing)) + 1]
play(toPlay)

here,

  1. autoPlayOrder is the list which has the songs to play
  2. playing is the song which is currently playing
  3. play() is a function I have that just plays the song

Now the system works as expected when the page is loaded but when im on another webpage, then when the song stops the next one isn't autoplayed...after some testing I concluded that this is due to the reason that javascript isnt allowed to run when the page is not active.

During my testing, I had the page active and the code did what it was supposed to...then I did the same thing but this time i switched the tab and so the next audio didnt autoplay as it was supposed to and as it had previously done..plus as soon as i switched back to the tab it started playing

Just another side note, I was almost facing the same issue when i tried to make a loop song feature, but managed to work around that by using the inbuilt loop feature in an audio element in html.


Solution

  • I found the solution, the <audio> tag in HTML has an inbuilt onended attribute in which we can pass our own function. So just create a function and pass that in the onended attribute and it will work even if the webpage is not active/loaded