2016-01-21 133 views
0

我想在背景中播放3次音频,3次后音频将自动停止。 我试过这段代码,它没有工作。 HTML代码:Javascript音频循环

<audio id='beep' controls> 
<source src="beep-02.mp3" type="audio/mpeg"> 
Your browser does not support the audio element. 
</audio> 

JAVASCRIPT:

var count = 1 
document.getElementById('beep').addEventListener('ended', function(){ 
    this.currentTime = 0; 
    if(count <= 3){ 
     this.play(); 
    } 
    count++; 
}, false); 

感谢。

+0

[这是一个重复(https://stackoverflow.com/questions/15423040/html5-play-audio-loop-4x-then-stop)。 – 2016-01-21 17:38:56

+0

当你说它不起作用时,它做了什么? – jasonwarford

+0

它可能肯定是重复的,但接受的答案是可疑的。除非你真的不能依赖'ended'事件,否则我不认为你需要依赖'setInterval或setTimeout'来匹配音频的持续时间。 – mczepiel

回答

1

你可以尝试使用onended: 参考:http://www.w3schools.com/tags/av_event_ended.asp或者它可能是你需要再次增加你的计数调用播放(前)

var count = 1; 
var audio = document.getElementById('beep'); 
audio.onended = function() { 
    if(count <= 3){ 
     count++; 
     this.play(); 
    } 
}; 
+0

添加一个侦听器为'结束'事件或为'onended'设置一个显式处理程序应该没有功能差异... – mczepiel

+0

我不是100%确定,但是如果您使用事件侦听器,我认为您必须调用bind )为了在函数内部使用'this'?例如:audio.addEventListener('keydown',function(e){this.handle_keydown(e); } .bind(this),false); 参考:http://stackoverflow.com/questions/13996263/javascript-scope-addeventlistener-and-this – Rosenumber14

+0

不,函数的上下文this将被设置为事件的currentTarget在这种情况下,这将是音频元素。 https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener“使用addEventListener()将处理函数附加到元素时,处理函数内部的值是对元素的引用。它与传递给处理函数的event参数的currentTarget属性的值相同。“ – mczepiel

0

试试这个:

var count = 0; 
document.getElementById('beep').addEventListener('ended', function(){ 
    if(count <= 3){ 
     this.play(); 
     count++; 
    } 
}, false); 
0

1)如果你确实想在后台玩,你还需要添加一个autoplay属性。

<audio id='beep' controls autoplay> 
    <source src="beep-02.mp3" type="audio/mpeg"> 
    Your browser does not support the audio element. 
</audio> 

2)这应该工作,你撰写非常多,但在某些浏览器可能需要重置播放头,如果你会:this.currentTime = 0

JAVASCRIPT:

var count = 0 
document.getElementById('beep').addEventListener('ended', function(){ 
    count++; 
    if (count < 3) { 
    this.currentTime = 0; // may be needed in some browsers to reset 
    this.play(); 
    } 
}, false); 

为了记录我以前有建议使用loop属性,并在ended之后简单停止发射3次,但是当我测试它时,loop会阻止ended发射。

http://jsfiddle.net/jorw3yfn/