[英]How can i dynamically load/play/pause multiple-source HTML5 audio on click?
I have a content slider, set to play / stop on each click. 我有一个内容滑块,设置为每次单击时播放/停止。
The problem: I want it to pause on second click. 问题:我希望它在第二次点击时暂停。 Right now it won't pause.
现在它不会暂停。 Any ideas?
有任何想法吗?
See site here: http://dev.alsoknownas.ca/music/ (audio branding section on homepage). 请参阅以下站点: http : //dev.alsoknownas.ca/music/ (主页上的音频品牌部分)。
Here's the code: 这是代码:
**Edited to reflect the code suggested by Lloyd below: **编辑以反映以下劳埃德建议的代码:
<audio id="player"></audio>
Here's the script: 这是脚本:
$(document).ready(function(){
$("span.1").attr("data-src","song.mp3");
$("span.2").attr("data-src","song2.mp3");
$("span.3").attr("data-src","song3.mp3");
$("span.4").attr("data-src","song4.mp3");
$("span.5").attr("data-src","song5.mp3");
});
$("span.1,span.2,span.3,span.4,span.5").click(function () {
var player = document.getElementById("player");
player.src = this.getAttribute("data-src");
player.play();
});
for this markup: 对于此标记:
<audio id="player"></audio>
<span class="1">one</span>
<span class="2">two</span>
use this script: 使用此脚本:
$("span.1")
.attr("data-src-mp3","song1.mp3")
.attr("data-src-ogg","song1.ogg");
$("span.2")
.attr("data-src-mp3","song2.mp3")
.attr("data-src-ogg","song2.ogg");
$("span[data-src-mp3]").click(function () {
var player = document.getElementById("player"),
$this = $(this);
if ($this.hasClass("selected")) {
if (player.paused) {
player.play();
} else {
player.pause();
}
}
else {
$("span[data-src-mp3].selected").removeClass("selected");
$this.addClass("selected");
$(player)
.empty()
.append($("<source>").attr("src", $this.attr("data-src-mp3")))
.append($("<source>").attr("src", $this.attr("data-src-ogg")))
player.play();
}
});
Live Demo: http://jsfiddle.net/75lb/8cGBx/ 现场演示: http : //jsfiddle.net/75lb/8cGBx/
Try this, 尝试这个,
Instead of doing 而不是做
$('audio').bind('play','pause', function() {
Do 做
$('audio').bind('play pause', function(event) {
According to your code, by default audio is paused, when user clicks, it starts playing, and on next click it pauses. 根据您的代码,默认情况下,音频会暂停,当用户单击时,音频会开始播放,而在单击时会暂停。
Hope this works for you. 希望这对您有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.