Search code examples
javascripthtmlaudio

Audio pause is not working where play working fine


I am trying to implement this method because I have a table of audio to play/pause individually, so I found this way after many research. But pause is not working here. Could anyone please help me?

function playAudio(url) {
        new Audio(url).play();
      }
function pauseAudio(url) {
        new Audio(url).pause();
      }
<input type="button" value="PLAY" onclick="playAudio('https://cldup.com/qR72ozoaiQ.mp3')" />         
<input type="button" value="PAUSE" onclick="pauseAudio('https://cldup.com/qR72ozoaiQ.mp3')" />


Solution

  • You should send the play/pause event to the audio tag (you can do it by setting an id to your audio element so you can target it for example) : https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/pause

    
    function playAudio(id) {
      document.getElementById(id).play();
    }
    function pauseAudio(id) {
      document.getElementById(id).pause();
    }
    
    
    <audio
        id='sound' 
        controls
        src="https://cldup.com/qR72ozoaiQ.mp3">
        Your browser does not support the
                <code>audio</code> element.
    </audio>
    <input type="button" value="PLAY" onclick="playAudio('sound')" />         
    <input type="button" value="PAUSE" onclick="pauseAudio('sound')" />