这是一个小的html文件,当我点击它时会创建一个计时器图像并播放计时器音乐。
<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>
我是JavaScript的新手,但这就是我想要的:
当用户点击图像时,音乐应该不停播放,直到用户再次点击图像为止。
我该怎么做?
答案 0 :(得分:2)
<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
});
}
答案 1 :(得分:1)
<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>
使用此代码在图像按钮上停止音频播放。 在源src中设置你的音频。