JavaScript停止按钮单击的音频
调用函数generate时,应该播放声音。如果按钮被触发,声音应该停止。什么是最好的方法来做到这一点?JavaScript停止按钮单击的音频
<script>
var audio = new Audio('assets/spin.mp3');
function generate()
{
/* some code goes here*/
audio.play();
}
</script>
<button onClick="game.rotationAngle=0; game.draw();generate();audio.stop();">start</button>
这是一种重置,我需要执行时,按钮被触发。这就是为什么需要在声音再次运行之前停止声音的原因。
- 你应该点击第n和(N + 1)个时间区分。要做到这一点,只需检查音频是否暂停。
- 使用
audio
在<script>
标记之外无效,因为您在脚本标记中定义它。 - 如果要开始追踪,还应该将当前时间设置为零。
下面是结果代码。
<script>
var audio = new Audio('assets/spin.mp3');
function generate() {
/* some code goes here*/
if(audio.paused) {audio.currentTime=0;audio.play()}
else audio.pause();
}
</script>
<button onClick="game.rotationAngle=0; game.draw();generate();">start</button>
我使用的脚本适用于某种'命运之轮'。为此,我需要在每次按下按钮时从头开始播放声音。你知道我的意思? –
@pele你的意思是重新开始?检查编辑。 – nicael
这工作正常,但它在调试器中显示我这个错误,当多次按下按钮。 http://puu.sh/pp6fV/972009d73e.png –
您可能需要使用audio.pause()
,而不是因为没有stop
方法。如果您检查Audio.prototype.stop
它是未定义的。
有没有这样的功能audio.stop()
。 您可以改用以下内容:
function generate() {
if(!audio.paused) { /* Check if it's not paused */
audio.pause(); /* To pause the audio */
audio.currentTime = 0; /* To reset the time back to 0 */
}
else {
audio.play(); /* To make it play again */
}
};
使用audio.pause()
,而不是audio.stop()
你是说,你确实想通过点击相同的按钮来触发启动/停止?创建一个变量(标志)并在点击时更改它的值。 – nicael
当我按下按钮时,在我的debuger中出现此错误:http://i.stack.imgur.com/95sEn.png –