fefe
fefe

Reputation: 9055

stop dynamically created Audio

I create dynamically on click event (play) audio element like this

var myAudio = document.createElement('audio');
myAudio.setAttribute('src', mp3link);

than I let it play

myAudio.play()

Now the problem comes when I click on another element and the next track starts to play, I would like to stop before all running audios in this case. How do I do that?

Upvotes: 1

Views: 814

Answers (3)

zer00ne
zer00ne

Reputation: 43990

  1. Collect all audio elements with querySelectorAll('audio') in a NodeList.
  2. Iterate through the NodeList with a for loop.
  3. On each iteration (loop), .pause() then reset the currentTime = 0. There's no stop() method, so you must pause then reset the time to 0.
    • In the Snippet, start the 2 players then the Play button.
    • Click the stopAll button.
    • Click the Play button again.

Basically, stop all players, then play the exact one you want. That's how it's done normally. Of course you'll have the dynamic players instead of the hard coded type, but the stopAll() function will work with the dynamically created audio as well.

SNIPPET

var xAudio = document.createElement('audio');
var mp3Link = 'http://glpjt.s3.amazonaws.com/so/av/pf-righteous.mp3'
xAudio.setAttribute('src', mp3Link);
document.body.appendChild(xAudio);

function play() {
  xAudio.play();
}

function stopAll() {
  var xGroup = document.querySelectorAll('audio');

  for (var i = 0; i < xGroup.length; i++) {
    xGroup[i].pause();
    xGroup[i].currentTime = 0;
  }
}
<body>
  <audio src="http://glpjt.s3.amazonaws.com/so/av/00.mp3" controls></audio>
  <audio src="http://glpjt.s3.amazonaws.com/so/av/balls.mp3" controls></audio>
  <br/>


  <button onclick="stopAll()">StopAll</button>
  <button onclick="play()">Play</button>
</body>

Upvotes: 1

Joey Etamity
Joey Etamity

Reputation: 866

Create only one <audio id="audio"></audio> in the html

var myAudio = document.getElementById('audio');
myAudio.setAttribute('src', mp3link);
myAudio.play()

Every time you clicked new track, it will replace the mp3 source link.

Upvotes: 0

brianxautumn
brianxautumn

Reputation: 1162

Don't call play directly. Make an object that has a property currentAudio. Give it a function play that takes an audio object as a parameter. When you hit play and pass it a new audio element, you can stop the old one before playing the new one, and save the reference.

Upvotes: 0

Related Questions