2个音频声音,我想一次播放一个HTML5音频元素

时间:2015-07-15 00:44:56

标签: javascript html5 audio

问题:我有2个音频声音,我想一次播放一个HTML5音频元素。

类似帖子:Play one HTML audio element at a time

我在问题中看到了类似的帖子。但是,作为JavaScript初学者,我不理解代码。所以我尝试了一种更简单的方法让我能理解,但是没有用。我很感激任何建议。

HTML5代码:(仅针对此示例,我使用与上一篇文章相同的音频源:http://jsfiddle.net/RE006/8djstmvy/

<div>
<h2>Example 1</h2>
<audio id="sound1" src=http://geo-samples.beatport.com/lofi/5005876.LOFI.mp3 controls="controls" preload="none">
<p>Your browser does not support the audio element.</p>
</audio>
</div>

<div>
<h2>Example 2</h2>
<audio id="sound2" src=http://geo-samples.beatport.com/lofi/5005933.LOFI.mp3 controls="controls" preload="none">
<p>Your browser does not support the audio element.</p>
</audio>
</div>

JavaScript的:

var $ = function (id) {
return document.getElementById(id);
}

var sound1_click = function() {
//starts playing
$("sound1").play ();
//pause playing
$("sound2").pause();
}

var sound2_click = function() {
//starts playing
$("sound2").play ();
//pause playing
$("sound1").pause();
}

window.onload = function () {
$("sound1").onclick = sound1_click;
$("sound2").onclick = sound2_click;
}

1 个答案:

答案 0 :(得分:0)

我认为问题是您列出的是click事件,当您应该收听play事件时,由于某种原因,window.onload在jsfiddle中无效,所以替换

window.onload = function () {
    $("sound1").onclick = sound1_click;
    $("sound2").onclick = sound2_click;
}

$("sound1").onplay = sound1_click;
$("sound2").onplay = sound2_click;

fiddle demo

或者你可以简单地概括一下:

var audios = document.getElementsByTagName('audio');
for(var i=0; i<audios.length;i++)    audios[i].onplay = pauseAllAudios.bind(null, audios[i]);

function pauseAllAudios(audio){
    for(var i=0; i<audios.length;i++)
        if(audios[i]!=audio)    audios[i].pause();    
};

fiddle demo