Preventing simultaneous playing of HTML5 Video and Audio elements
Using HTML5 I have 2 Audio elements and 1 video element on a page. Quite simply I'd like to add JavaScript functionality tha开发者_StackOverflow中文版t prevents them from being played simultaneosly. My main problem is how to target the click events of the default player. The HTML is below, thanks;
<section id="mp3Section">
<h2>MUSIC</h2>
<ul>
<li>Lovers Pass<audio id="audioLP" controls="controls" preload="auto" autobuffer>
<p class="redText">Sorry. Your browser does not support this audio element</p>
<source src="music/loversPass.mp3" />
<source src="music/loversPass.wav" />
</audio></li>
<li>All The Fun<audio id="audioATF" controls="controls" preload="auto" autobuffer="autobuffer">
<p class="redText">Sorry. Your browser does not support this audio element</p>
<source src="music/allTheFun.mp3" />
<source src="music/allTheFun.wav" />
</audio></li>
</ul>
</section>
<section id="videoSection">
<h2>Video</h2>
<video id="vidScreen" controls poster="images/vidThumb.jpg">
<source src="videos/loversPassOGV.ogg"/>
<source src="videos/loversPassVid.mp4" />
</video>
</section>
How I'd do it (using jQuery for simplicity, though not required):
$('audio,video').bind('play', function() {
activated = this;
$('audio,video').each(function() {
if(this != activated) this.pause();
});
});
The audio
and video
elements have events that you can catch. See for example https://developer.mozilla.org/En/Using_audio_and_video_in_Firefox .
You could probably do something like this (untested):
var allMediaIds = ["audioLP", "audioATF", "vidScreen"];
var allMedia = [];
for (var i = 0, len = allMediaIds.length; i < len; i++) {
allMedia.push(document.getElementById(allMediaIds[i]));
}
function loopAllMedia(callback) {
for (var i = 0, len = allMedia .length; i < len; i++) {
callback(allMedia[i]);
}
}
loopAllMedia(function(element) {
element.addEventListener("play", function() {
loopAllMedia(function(otherElement) {
if (element != otherElement)
otherElement.pause();
});
});
});
精彩评论