Getting my iPhone music app to keep playing on the lock screen
I mostly use my private music app on an iPhone, added to the home screen, with the phone locked in my pocket. For a music app, two things are the bare minimum: When a track ends on the lock screen, the next one starts. The lock screen and Dynamic Island show previous and next buttons. Both sound basic. In a home-screen web app on iOS, both took me far longer than I expected. What I tried first A…
For a music app on an iPhone, the lock screen and Dynamic Island display previous and next buttons. The app's ability to seamlessly transition to the next track upon completion without user intervention proved challenging. Initially, adding a brief silent clip between tracks and using background timers did not consistently achieve the desired outcome.
Registering buttons again after playback initiation improved the situation temporarily but proved unreliable. The source material highlights a WebKit bug affecting iOS versions where when an audio element reaches its natural end and there is no audio playing, WebKit terminates the app's audio session, causing the next track to pause until the app is opened.
This explains why the endless silent audio helped in the past as it maintained the session continuously. However, a more straightforward approach involves ensuring the music itself never ends. By looping the audio element and implementing event listeners to detect seeking actions, the app can detect when a track restarts from the beginning and proceed to play the next track.
The fix involves ensuring the audio element always loops, catching the jump back to the start, and handling seeks, pauses, and changes in track source within the same event rather than relying on timers. Additionally, registering previous and next action handlers again after the audio element enters the 'Now Playing' state ensures the lock screen correctly displays the previous and next buttons.
This solution addresses the issue comprehensively, allowing the iPhone music app to transition between tracks without user intervention, with the lock screen and Dynamic Island accurately reflecting the current position.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.