How to make a mobile browser play a list of audio files without stopping when the screen is locked?

345 Views Asked by At

I would like to have a web page being able to act like a music player.

The user enqueues a list of audio files (hosted on the server) and they start playing. When the first audio is over, the second begins, etc, until the last one.

I was able to easily implement this functionality using an <AUDIO> element, and replacing its src attribute with Javascript by adding an event listener on the ended event.

The problem is that this does not work consistently on mobile, because once the screen is locked, the Javascript does not keep executing. It may work for one song or two, but at some point it stops "skipping" to the next audio track.

From my understanding, this behaviour is caused by the fact that mobile browsers stop the Javascript event loop after some time to save battery when the screen is locked. I am aware of the Screen Lock API, I assume keeping the screen always on would solve my problem, but I don't want to keep the screen always on.

I could delegate playing audio files to a web worker, which should theoretically keep running in the background. Still, I'm not sure it won't be stopped when the screen is locked, and most importantly I am not sure it can even play sounds.

Is there anything similar to the Screen Lock API that allows me to ask permission to keep scripts executing also when the screen is locked?

If not so, how could I overcome this problem?

1

There are 1 best solutions below

0
leonixyz On

After some research, I discovered that the act of killing the javascript event loop is highly browser-specific.

Chrome for Android seem to let the playback run indefintely. Firefox for Android is stricter, and kills the event loop.

The System Wake Lock looks like a promising API for solving the above problem. At the moment, the W3C is still in process of collecting use cases in order to be able to define a new standard:

https://github.com/w3c/system-wake-lock/issues/4