当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Trouble with HTML5 audio loop

问题描述:

I'm having trouble getting HTML5 audio to loop on my website: http://oclock.webs.com.

(It's an alarm which, when the alarm goes off, is supposed to loop a 1 second alarm sound over and over until you click OK on the alert box).


Simply including "loop" in the audio tag wasn't doing anything.

I found a helpful post on StackOverflow which lead me to this website: http://forestmist.org/2010/04/html5-audio-loops/

I knew Method 1 and 2 wouldn't work for me since they don't work on Firefox and are iffy on Chrome, and so Method 3 should have worked, unfortunately it didn't. Method 3 works when I'm on that website's page, but not when the code is included in my own page so I think there may be some conflicting code.


Relevant part of my webpage:

<audio id="audio1" preload>

<source src="media/alarm.ogg" type="audio/ogg" />

<source src="media/alarm.mp3" type="audio/mpeg" />

</audio>

<audio id="audio2" preload>

<source src="media/alarm.ogg" type="audio/ogg" />

<source src="media/alarm.mp3" type="audio/mpeg" />

</audio>

Relevant Javascript of the page:

if(timer==true && hours==hv && mins==mv && secs==sv){

document.getElementById("audio1").play();

alert("o'clock: Alarm ringing!");

document.getElementById("alarm").value="Set Alarm";

document.getElementById('audio1').addEventListener('ended', function(){

this.currentTime = 0;

this.pause();

document.getElementById('audio2').play();

}, false);

document.getElementById('audio2').addEventListener('ended', function(){

this.currentTime = 0;

this.pause();

document.getElementById('audio1').play();

}, false);

}

else{

document.getElementById("audio1").pause();

document.getElementById("audio2").pause();

document.getElementById("audio1").currentTime = 0;

document.getElementById("audio2").currentTime = 0;

}

Intention: Upon the computer's time matching that of the selected time on the page, the audio alarm will repeat (loop) until the user clicks OK on the alert box popup.

Problem: Currently it only plays through the audio once, it doesn't loop. Where did I mess up?

网友答案:

"ended event" or "loop" property dose not work on some browsers. So I used window.setInterval() for looping audio playing.

For this method, you should know play time of Audio file in advanced.

function playAudioWithLoop (/**HTMLAudioElement*/audio, /**Number*/length)
{
    function onEnd (){
        audio.play();
    }

    /* length is msec */
    if(length > 0) {
        audio.__timer = window.setInterval(onEnd, length);
    }
}

function stopAudioWithLoop (/**HTMLAudioElement*/audio)
{
    if(audio.__timer) {
        audio.__timer = window.clearInterval(audio.__timer);
    }
}

======================================================================

***playAudioWithLoop(document.getElementById("audio1"), 12*1000);***
***stopAudioWithLoop(document.getElementById("audio1"));***
分享给朋友:
您可能感兴趣的文章:
随机阅读: