javascript javascript慢慢降低音频元素的音量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7942452/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript slowly decrease volume of audio element
提问by istan
audio element is playing with volume:
音频元素正在播放:
audio.setVolume(.20)
At a certain point I want to fade out the volume, rather than have it cut abruptly, so in essence I want
在某个时候我想淡出音量,而不是突然削减它,所以本质上我想要
audio.setVolume(.15)
audio.setVolume(.10)
audio.setVolume(.05)
audio.setVolume(.03)
audio.setVolume(.01)
but there needs to be some very brief delay in between these changes so they are audible and I get my fade out effect. What is the proper way to do this?
但是在这些变化之间需要有一些非常短暂的延迟,这样它们才能被听到并且我得到了我的淡出效果。这样做的正确方法是什么?
thanks!
谢谢!
回答by Michael Berkowski
You could use a setInterval()
:
你可以使用一个setInterval()
:
// Initial volume of 0.20
// Make sure it's a multiple of 0.05
var vol = 0.20;
var interval = 200; // 200ms interval
var fadeout = setInterval(
function() {
// Reduce volume by 0.05 as long as it is above 0
// This works as long as you start with a multiple of 0.05!
if (vol > 0) {
vol -= 0.05;
audio.setVolume(vol);
}
else {
// Stop the setInterval when 0 is reached
clearInterval(fadeout);
}
}, interval);
回答by xmarcos
I would wrap the setTimeout
inside of the function, as well as the options. Regarding the factor, 0.01
will be a safe value to decrease without you having to know or adjust the initial value.
我会包装setTimeout
函数的内部以及选项。关于该因素,0.01
将是一个安全值,无需知道或调整初始值即可减少。
function fadeVolume(volume, callback)
{
var factor = 0.01,
speed = 50;
if (volume > factor)
{
setTimeout(function(){
fadeVolume((audio.volume -= factor), callback);
}, speed);
} else {
(typeof(callback) !== 'function') || callback();
}
}
fadeVolume(audio.volume, function(){
console.log('fade complete');
});
Once the fade is complete, it will fire a callback that you can use to play the next song.
淡入淡出完成后,它会触发一个回调,您可以使用它来播放下一首歌曲。
回答by Afzaal Ahmad Zeeshan
You can use this mouse key event too.
您也可以使用此鼠标键事件。
audio.on('keydown', function() {
// and here keep increasing or decreasing the volume, untill keyUp
})
As being viewed, its jQuery! You can use it for your work. Also, the audio tag is for the div, that contains the audio tag!
在查看时,它的 jQuery!您可以将其用于您的工作。此外,音频标签用于包含音频标签的 div!