Reputation: 9055
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
Reputation: 43990
querySelectorAll('audio')
in a NodeList.for
loop..pause()
then reset the currentTime = 0
. There's no stop()
method, so you must pause then reset the time to 0.
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.
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
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
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