AggieIE
AggieIE

Reputation: 125

Loop Audio in Javascript Until Alert Dismissed

I've been doing some research and haven't found anything helpful to explain/lead me in the right direction. This is what I have so far. It works but the alert only plays for the preset time. I want it to play until the "Ok" button on the alert is clicked. Thanks

<script type="text/javascript">

setInterval(function(){   
var old_count=<?php echo $arr['counter'];?>;
var audio=document.getElementById('audiotag1');
    $.ajax({
        type : "POST",
        url : "dbcheck.php",
        timeout: 4000,
		
        success : function(data){
            if (data > old_count) {
                alert('New Hot Part Has Been Entered.');
		document.getElementById('audiotag1').play();
		old_count=data;
				
		window.setTimeout(function(){ 
		       location.reload();
		}, 10000);
            }

        }
    });
	
},5000);

</script>

<audio id="audiotag1" src="alert.wav" preload="auto"></audio>

Upvotes: 0

Views: 683

Answers (2)

mido
mido

Reputation: 25034

quite easy to implement when you use a flag for audio looping and listen to the ended event of the audio element.

audio.addEventListener('ended', function(){
    if(loopAudio){
        audio.play();
    }
});
...
// where you trigger the alert.
loopAudio = true;
audio.play();        
alert('click ok to stop audio looping.');
loopAudio = false;
audio.pause(); // if you want
...

Fiddle Demo

Upvotes: 1

Nithyakumaran
Nithyakumaran

Reputation: 53

I tried creating a static version (html) of your problem. If you set the loop parameter of the audio to true. The audio does not stop even when an alert box opens up. I have pasted my code below. Let me know if I misunderstood your question.

<!DOCTYPE html>
<html>
<head>
<title>Audio Loop</title>
</head>

<body onload="onload()">
<input type="text" value="1"> </input>
<audio id="audiotag1" src="alert.wav" preload="auto" ></audio>
<input type="button" value="ok" onclick="stopAudio()"></input>
</body>
<script>


function onload(){
var old_count=document.getElementById('counter');
var audio=document.getElementById('audiotag1');
audio.loop=true;
audio.load();
audio.play()
}
function stopAudio(){
alert("Before Pause");
var audio=document.getElementById('audiotag1');
audio.pause();
}
</script></html>

Upvotes: 0

Related Questions