Home  >  Q&A  >  body text

How do I make the play/pause button work properly in Safari?

I have a situation with a small button that works on Chrome but not on Safari. I've tried trying autoplay in different places with no success. What am I missing here? Please note that I do not have sounds posted online to share. I was initially using Base64 encoded sound files. If I could find a shorter one, I would edit this post, but SO's editor limits my posts to include this one.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>音频播放和暂停</title>
  <link rel="stylesheet" href="styles.css">
</head>

<body>
  <audio id="audioElement" preload="auto">
    <source src="sound.mp3" type="audio/mpeg">
  </audio>
  <button id="playPauseButton" onmousedown="playAudio()" onmouseup="pauseAudio()" ontouchstart="playAudio()" ontouchend="pauseAudio()">播放/暂停</button>

  <script>
    function playAudio() {
      document.getElementById("audioElement").play();
    }

    function pauseAudio() {
      document.getElementById("audioElement").pause();
    }
  </script>
</body>

</html>

Here is a link to a JS Fiddle if it helps. Thanks.

https://jsfiddle.net/anonymouspenguin/kevhq7x1/1/

P粉323224129P粉323224129409 days ago742

reply all(1)I'll reply

  • P粉659378577

    P粉6593785772023-09-07 10:42:58

    I'm not sure how to debug in Safari, but in Google Chrome I click on the ellipsis (3 vertical dots icon), select Settings, then Developer Tools.

    Go to console>Clear console>Click your button

    I got this error. The two onmouseup and ontouchpad properties in your button label conflict with other properties. Please remove them. Once playback is working properly, find the next error and continue.


    Instead of putting the attributes in the button HTML tag, you can try this:

    const button = document.getElementById("playPauseButton");
    
    button.addEventListener('mousedown', () => {
      document.getElementById("audioElement").play();
    });
    
    button.addEventListener('mouseup', function () {
      document.getElementById("audioElement").pause();
    });

    reply
    0
  • Cancelreply