S Sahoo
S Sahoo

Reputation: 29

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')" />

Upvotes: 1

Views: 1214

Answers (2)

Mohammad Ali Rony
Mohammad Ali Rony

Reputation: 4905

You have created two objects so it does not pause the same object.

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

Upvotes: 1

Nico_
Nico_

Reputation: 1386

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')" />

Upvotes: 1

Related Questions