如何使用jQuery和HTML5检测音频文件的结尾
我有这个jQuery code和HTML工作确定一个英语培训网站。
I've got this jquery code and html to work OK for an English language training site.
$(document).ready(function() {
$("p").hover(
function() {
$(this).css({"color": "purple", "font-weight" : "bolder"});
},
function() {
$(this).css({"color": "black", "font-weight" : ""});
}
);
$("p").click(function (event) {
var element = $(this);
var elementID = event.target.id;
var oggVar = (elementID +".ogg");
var audioElement = document.createElement('audio');
audioElement.setAttribute('src', oggVar);
audioElement.load();
audioElement.addEventListener("load", function() {
audioElement.play();
}, true);
audioElement.play();
});
});
<div>
<p id="one"> this is the first paragraph</p>
....
<p id="four"> this is the fourth paragraph</p>
....
</div>
的
问题是,如果被点击文本而音频文件正在播放(或双点击)然后在第二文件(或相同的文件)开始播放。所以,我结束了两个文件同时播放。我需要prevent这一点。我认为,结束事件是相关的,但是,尽管看起来一些例子,我看不到相当如何检测,如果一个文件播放,并等待,直到它完成允许第二个文件,以启动(或甚至prevent前它打的话)。任何帮助将是非常美联社preciated :)
the problem is that if text is clicked on while an audio file is playing (or double clicked) then the second file (or the same file) starts playing. So I end up with two files playing simultaneously. I need to prevent this. I think that the 'ended' event is relevant but, despite looking some examples, I can't see quite how to detect if a file is playing and wait until it's finished before allowing a second file to start (or even prevent it from playing at all). Any help would be much appreciated :)
您可以添加事件侦听器的的结束,打事件。另外,为什么创造通过JavaScript一个音频标签?我只想创建一个空的隐藏式音响标签:
You can add event listeners for the ended and playing events. Also, why creating a audio tag via javascript? I would just create an empty hidden audio tag:
<audio id='myAudio' autoplay='autoplay'></audio>
您有两种选择:
- 禁用/启用时,音频播放/停止按钮/链接(preferred恕我直言)
- 忽略点击时已经弹奏
那么双事件监听器添加到它:
Then add two eventlisteners to it:
var playing = false;
$('#myAudio').on('playing', function() {
playing = true;
// disable button/link
});
$('#myAudio').on('ended', function() {
playing = false;
// enable button/link
});
$("p").click(function (event) {
if(!playing) {
var element = $(this);
var elementID = event.target.id;
var oggVar = (elementID +".ogg");
var audioElement = $('#myAudio')[0];
audioElement.setAttribute('src', oggVar);
audioElement.play();
}
});