Overcoming Audio Playback Issues on mobile(iOS) with Phoenix LiveView - Seeking Better Solutions

Hello, everyone!

I recently encountered an issue with audio playback in a Phoenix LiveView application that I thought I’d share. I believe it could be a common issue many of us may face, particularly when dealing with user interactions on different browsers and devices, specifically iOS mobile browsers in this case.

The Issue:

My application has an audio playback feature. I had implemented this feature using a custom Phoenix LiveView event, playAudio, handled in a JS Hook. The relevant JavaScript code looked something like this:

javascriptCopy code

this.handleEvent("playAudio", ({ audio_id, audio_url }) => {
    let audio = document.getElementById(`audio-${audio_id}`);
    audio.src = audio_url;
    audio.addEventListener("loadeddata", () => {

also tried just put audio.play() in handleEvent without “loadeddata” event, but still failed.

This code worked perfectly on desktop browsers but failed on all iOS mobile browsers. I hypothesized that this was due to audio.play() not being able to be triggered inside the custom LiveView event playAudio.

The Solution:

I found out that on mobile browsers (especially iOS), audio playback might need explicit user interaction. I had to modify the code to directly play the audio on user interaction, not waiting for the loadeddata event. My working solution was to use the traditional onclick handler directly on the HTML element to trigger audio playback:

htmlCopy code

<a href="#" class="text-blue-600 hover:mb-2 hover:text-blue-800" onclick={"document.getElementById('audio-#{word.id}').play()"} phx-click="playAudio" phx-value-audio-id={word.id} phx-value-audio-text={word.word}>
    <!-- SVG for the play button -->
<audio controls id={"audio-#{word.id}"}>
    <p>Your browser does not support HTML audio</p>

By doing this, clicking the play button triggers the audio to play directly, bypassing the LiveView event. This works across all browsers, including iOS mobile browsers.

Seeking Better Solutions:

While this solution works, it might not be the most elegant or efficient one. I am very much interested to hear if anyone else has encountered similar issues and how you’ve dealt with them. Is there a better approach to handle audio playback in Phoenix LiveView applications, particularly compatible across all devices and browsers?

Thank you for your time!


For what it’s worth, this isn’t a LiveView-specific problem, it’s a fundamental limitation of how autoplay is handled in the browser: