如何使用javascript停止声音

问题描述:

我在我的html文件中有一个声音文件。我想停止使用JavaScript 30秒后打它,下面是发挥如何使用javascript停止声音

var snd = new Audio("sound location"); 
snd.play(); 

任何帮助的代码?

+1

看看https://developer.mozilla.org/en-US/docs/Web/ API/window.setTimeout并使用snd.pause功能 –

你可以这样做:

setTimeout(function() { 
    snd.pause(); 
}, 30000); 
+0

或者只是'setTimeout(snd.pause,30000)'? –

+0

不,@Derek*,**不**工作。我认为答案很简单。 – iConnor

+0

@Pinocchio - 为什么不呢? –

window.setTimeout(snd.pause.bind(snd), 30000); 
+2

如果snd.pause'被'window'调用为'this',办法。也许'snd.pause.bind(snd)会工作。 –

+0

感谢您的评论 –

+0

@mikeSamuel是正确的,但它使0意义上做到这一点。 – iConnor

的HTML5音频元素有几个方法,你应该知道的。

audioElement.pause(); // Will pause the audio 

audioElement.play(); // Will play the audio 

audioElement.volume = 0.5; // Will set the volume to half of max 

audioElement.load(); // Will start to load the media 

audioElement.currentTime = 0; // Will set the time of the audio to 0 

如果你不想停止那里的音频,你可以做这样的事情。

audioElement.pause(); 
audioElement.currentTime = 0; 

因此,要回答你的问题,你可以使用setTimeout停止方式

window.setTimeout(function(){ 
    audioElement.pause(); 
    audioElement.currentTime = 0; 
}, 30 * 1000);