html5音频addeventhandler

时间:2016-09-10 09:40:35

标签: javascript html5

我制作了一个带有限循环功能的html5 audioplayer,但是当我想用按钮替换audioplayer并为它们添加一个事件处理程序时,我无法保持这个功能。在此示例中,必须选中复选框,并且必须在重复功能工作之前选择selectmenu的第二个选项。不知何故,当我添加时,repeat-function停止工作: “document.getElementById(”Play“)。addEventListener(”click“,myFunction);”。如果我删除它,代码可以工作,但只有当我使用html audioplayer本身时。  我的代码:

<!DOCTYPE html> 
<html> 
<body> 

<span style="font-family:arial; font-size:16px;"><b>Pre:</b></span>
<input id="precount" type="checkbox"><br><br>
<span style="font-family:arial; font-size:16px;"><b>Repeat:</b></span>
<select>
<option id="ok1">1x</option>
<option id="ok2">2x</option>
<option id="ok3">3x</option>
</select><br><br>

<audio id="myAudio" controls>
<source src="http://u1259p183.web0080.zxcs.nl/jQuery.mmenu-master/demo/sortablemenumobile/range_items/audio_notes/10_a.mp3">
</audio>

<script>
function PlaySound(soundobj) {
var thissound=document.getElementById(soundobj);
thissound.play();
}
function PauseSound(soundobj) {
var thissound=document.getElementById(soundobj);
thissound.pause();
}
</script>

<form>
<input type="button" value="PlaySound" id="Play">
<input type="button" value="PauseSound" id="Pause">
</form>


<script>

document.getElementById("Play").addEventListener("click", function);
var loopLimit = 2;
var loopCounter = 0;
var aud = document.getElementById("myAudio");
aud.onended = function() {
if ((loopCounter < loopLimit) &&    (document.getElementById("ok2").selected==true) &&(document.getElementById("precount").checked==true)){
this.currentTime = 0;
this.play();
loopCounter++;
}
};
</script>

</body> 
</html>

1 个答案:

答案 0 :(得分:0)

使用事件侦听器更改行,并将变量定义放在其前面:

var aud = document.getElementById("myAudio");
var loopLimit = 2;
var loopCounter = 0;
document.getElementById("Play").addEventListener("click", function (){
    loopCounter = 0;
    aud.play();
});