HTML5 - 如何在另一个音频标签开始播放时停止音频?

HTML5 - how to stop audio when another audio tag starts playing?

我有这个 javascript 功能:

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;
}

这个 html5 音频播放器在 Yii2 中的 Gridview 小部件内循环播放(它创建了许多播放器,每个播放器都有不同的歌曲):

'value'=> function ($data){                      
    return "<audio controls>
            <source src='" . $data->ficheiro . "' type='audio/mp3' />
            </audio>";
},

问题是当我正在播放一个音频标签并单击另一个的播放按钮时,它不会停止之前播放的音频标签并开始播放新的音频标签。两个音频标签同时播放。我正在尝试调整 javascript 函数,但它不起作用。

我也试过声明 var thisound = $('audio');

同样不行。

我需要在音频标签中添加 ID 吗? 我需要将 onClick='EvalSound' 事件关联到音频标签吗?

您没有识别 <audio> 标签的唯一方法。使用通用的 $("audio") 选择器会使问题变得更糟。对所有标签使用 id 并使其以这种方式工作。

好的,我是这样解决的:

addEventListener 抓取开始播放的音频,for 循环暂停所有其他音频标签。

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);