Why Can't JavaScript .Play() Audio Files on iPhone Safari

Why can't JavaScript .play() audio files on iPhone safari?

iOS disables autoplay, instead requiring that play be initiated as part of a user interaction (e.g., you can start playback within a touchstart listener). There's a bit of documentation about this on Apple's developer documentation. There's also this article Overcoming iOS HTML5 audio limitations on IBM's developer site that has examples and more detail.

Trying to play an .mp3 via JS on iOS browsers?

I am not sure if this is documented anywhere (I didn't stumble across it), but after some additional testing I discovered that iOS prohibits use of the .play() function on an existing HTML <audio> element or JS Audio() element, unless called directly and synchronously as the result of a user UI event. In other words, this will work:

const button = document.getElementById('my-button')
const audio = document.getElementById('my-audio')
button.addEventListener('click', () => {
audio.play()
})

But this will not work:

const button = document.getElementById('my-button')
const audio = document.getElementById('my-audio')
button.addEventListener('click', () => {
setTimeout(() => { audio.play() }, 1000)
})

Thus, having the .play() call in an async callback breaks playback on iOS.

However, as mentioned in a comment on this answer here: https://stackoverflow.com/a/54432573/983173, if you instantiate your audio element within a synchronous user interaction event handler, you can re-use and re-play (e.g. .play()) an Audio() element as much as you like. For example:

const button = document.getElementById('my-button')
let audio = null
button.addEventListener('click', () => {
audio = new Audio('myAudio.mp3')
// Works because `audio` itself was created synchronously during user event handler
setTimeout(() => { audio.play() }, 1000)
})

HTML5 Audio object doesn't play in Safari

About iPhone Safari: It seems play() work when launched by an onclick event.
See http://groups.google.com/group/iphonewebdev/browse_thread/thread/91e31ba7ae25e6d4?hl=en

Html 5 Audio is not working in iphone safari browser

Did like below code and solved problem

Added two lines before play

audio1.load();
audio2.load();

audio1.play();
audio1.on('ended' function(){
audio2.play();
});


Related Topics



Leave a reply



Submit