I have this javascript function:
var currentPlayer;
function EvalSound(soundobj) {
var thissound = document.getElementById(soundobj);
if (currentPlayer && currentPlayer != thissound) {
currentPlayer.pause();
}
if (thissound.paused) {
thissound.play();
} else {
thissound.pause();
}
thissound.currentTime = 0;
currentPlayer = thissound;
}
And this html5 audio player repeating in a loop inside a Gridview widget in Yii2 (it creates many players each of them with a different song):
'value'=> function ($data){
return "<audio controls>
<source src='" . $data->ficheiro . "' type='audio/mp3' />
</audio>";
},
The problem is when I have an audio tag playing and click on the play button of another it doesn't stop the previous playing audio tag and starts the new one. Both audio tags play at the same time. I'm trying to adapt the javascript function but it doesn´t work.
I also tried declaring var thisound = $('audio');
It also does not work.
Do I need to put an ID in the audio tag?
Do I need to associate an onClick='EvalSound'
event to the audio tag?
I have this javascript function:
var currentPlayer;
function EvalSound(soundobj) {
var thissound = document.getElementById(soundobj);
if (currentPlayer && currentPlayer != thissound) {
currentPlayer.pause();
}
if (thissound.paused) {
thissound.play();
} else {
thissound.pause();
}
thissound.currentTime = 0;
currentPlayer = thissound;
}
And this html5 audio player repeating in a loop inside a Gridview widget in Yii2 (it creates many players each of them with a different song):
'value'=> function ($data){
return "<audio controls>
<source src='" . $data->ficheiro . "' type='audio/mp3' />
</audio>";
},
The problem is when I have an audio tag playing and click on the play button of another it doesn't stop the previous playing audio tag and starts the new one. Both audio tags play at the same time. I'm trying to adapt the javascript function but it doesn´t work.
I also tried declaring var thisound = $('audio');
It also does not work.
Do I need to put an ID in the audio tag?
Do I need to associate an onClick='EvalSound'
event to the audio tag?
2 Answers
Reset to default 7Ok, here is how I solved it:
The addEventListener
grabs the audio beginning to play and the for
loop pauses all other audio tags.
document.addEventListener('play', function(e) {
var audios = document.getElementsByTagName('audio');
for (var i = 0, len = audios.length; i < len; i++) {
if (audios[i] != e.target) {
audios[i].pause();
}
}
}, true);
You don't have a unique way of identifying the <audio>
tags. And using a generic $("audio")
seelctor makes the issue worse. Use id
for all the tags and make it work that way.