简体   繁体   中英

Audio on ios does not work properly, it only works the first time

I have a problem with playing audio on IOS devices... the code I use is this to activate/deactivate the sound:

 <audio id="audio">
    <source src="sounds/fart.mp3" type="audio/mpeg" />
    Your browser does not support the audio element.
 </audio>
 <button id="audio-btn" class="audio-btn" onclick="toggleAudio()">
    <img id="audio-icon" src="img/sound-off.webp" alt="audio_play/pause" />
 </button>



let audioIconPlay = false;

 function toggleAudio() {
   const audioIcon = document.getElementById('audio-icon');
   audio.autoplay = true;
   audioIconPlay = !audioIconPlay;
   if (audioIconPlay) {
     audioIcon.src = 'img/sound-on.webp';
   } else {
     audioIcon.src = 'img/sound-off.webp';
   }
 }

And this when I click the button to play the audio:

 <button
  onmousedown="playMyAudio()"
  onmouseup="playMyAudio()"
 >
  Fart
 </button>

 function playMyAudio() {
   if (audioIconPlay && audio.paused) {
     audio.play();
   } else {
     audio.pause();
     audio.currentTime = 0;
   }
 }

Ps.: I did it all on onTouch as well

Now, on android devices it works, every click plays the audio, while on iOS it works only on the first click? There is a solution: I tried this: Allow audio.play() on safari for chat app but it does not work.

When you click the button, the function is executed and the sound is played. But at the mouseup event, the function is executed again and the sound is then stopped. Have you tried it with an onclick, so the function will run only once? Or should the sound only be played while pressing the button?

By the way, the equivalent for onmousedown on touchscreen devices is ontouchstart, and the equivalent of onmouseup is ontouchend. But I suggest to use onclick.

I did some tests, in practice it works but not immediate as with android.... My problem is that the audio I use is too short, it lasts a second. maybe even less.., So on the iphone it doesn't have the time to play such a short sound and it seems that it plays it only once but in reality it always does it only that the other times it is not heard as it does not have the time necessary to stop and play it all over again, I tried to insert a longer audio and it works. the problem is that if I click quickly several times on the button I do not get the same result as I have on android. i,e, stop the audio, reset the time and play it again. I have no idea of the because but it seems that iphone is delayed and unable to do it, while on android devices yes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM