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" 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
onm ousedown="playMyAudio()"
onm ouseup="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.
CodePudding user response:
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 onm ousedown on touchscreen devices is ontouchstart, and the equivalent of onm ouseup is ontouchend. But I suggest to use onclick.
CodePudding user response:
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.