Reputation: 35275
Here is a small html file which creates a timer image and plays a timer music when I click it.
<html>
<head>
<script language="javascript" type="text/javascript">
function playSound(soundfile) {
document.getElementById("dummy").innerHTML = "<embed src=\"" + soundfile + "\" hidden=\"true\" autostart=\"true\" loop=\"false\" />";
}
</script>
</head>
<body>
<table width="100%" height="100%">
<tr>
<td align="center" valign="middle">
<a href="#" onclick="playSound('timer.mp3');">
<img src="timer.png"/>
</a>
</td>
</tr>
</table>
<span id="dummy"></span>
</body>
</html>
I am new to JavaScript but here is what I want:
When the user click the image the music should be played non-stop until the user clicks the image again.
How do I do this?
Upvotes: 0
Views: 128
Reputation: 94319
<audio id="player" controls="controls"></audio> Remove "control" if you don't
<button onClick="playFile('timer.mp3')">Play/Stop</button> need it.
var playing = false; //pre set plaing to false
function playFile(n){
var player = document.getElementById("player"); //get the <audio>
player.src = n; //set the url
playing = !playing; //flip the status
playing ? player.play(): player.stop(); //play/stop
player.addEventListener("ended", function(){ //When ended,
player.play(); //play again
//do other stuff
});
}
Upvotes: 2
Reputation: 1214
<audio id="myAudio" controls preload loop>
<source src="http://media.w3.org/2010/07/bunny/04-Death_Becomes_Fur.mp4" type='audio/mp4'>
<source src="http://media.w3.org/2010/07/bunny/04-Death_Becomes_Fur.oga" type='audio/ogg; codecs=vorbis'>
Your user agent does not support the HTML5 Audio element.
</audio>
<img src="img/ex1.png" onclick="aud_play_pause()"/>
<script>
function aud_play_pause() {
var myAudio = document.getElementById("myAudio");
if (myAudio.paused) {
myAudio.play();
} else {
myAudio.pause();
}
}
</script>
use this code for non stop audio play on image button. set your audio in source src.
Upvotes: 1