Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mobile Safari skips first seconds of HTML Audio on play()

I have an React Audio Player that uses a useAudio hook to manage the HTML5 audio. It works fine everywhere except Mobile Safari, where the sound begins a few seconds after the player starts playing.

What's odd is that I'm checking canplaythrough on the element before calling HTMLAudioElement.play(). So Safari fires canplaythrough and starts "playing" the audio, except that the audio doesn't actually start until a second or so in.

Here's a complete example on CodeSandbox: https://codesandbox.io/s/useaudioplayer-jvftw?file=/src/useAudio.tsx

To replicate, open in Mobile Safari and play the Audio.

like image 454
Justin Smith Avatar asked Jan 29 '21 10:01

Justin Smith


People also ask

How do I get HTML audio to play on my website?

Complete HTML/CSS Course 2022 To play sound file in the background on a web page, use the <embed>… </embed> element. Also, use the autoplay attribute. This will run music in the background whenever the page loads.

What is the correct HTML for playing audio files?

The HTML <audio> element is used to play an audio file on a web page.

How do I stop audio from playing HTML?

Audio pause() Method The pause() method halts (pauses) the currently playing audio. Tip: This method is often used together with the play() method. Tip: Use the controls property to display audio controls (like play, pause, seeking, volume, etc, attached on the audio).


1 Answers

In my case audio would play ok the 1st time.
And from the 2nd time and on, safari would skip some initial seconds.

Solved it by calling
myAudio.load();
just before
myAudio.play();

like image 91
pok_net Avatar answered Oct 28 '22 21:10

pok_net