点击即可逐步关闭音频

时间:2015-07-10 02:20:50

标签: javascript html audio volume

我在自动播放中有一首引擎歌曲,我希望当我点击我的按钮时,声音会“逐渐”关闭以获得音量的流量减少并以0.1或0.2的音量完成,有人有个主意吗? 这是我的实际代码:

<audio autoplay>
   <source src="../audio/2445.mp3">
</audio>

<button>turn off</button>

1 个答案:

答案 0 :(得分:1)

不确定这是否是正确的方法,你可以这样做:

<audio autoplay id='aud'>
   <source src='http://upload.wikimedia.org/wikipedia/commons/5/5b/Ludwig_van_Beethoven_-_Symphonie_5_c-moll_-_1._Allegro_con_brio.ogg'>
</audio>

<button id='btn'>turn off</button>

JS:

var audio = document.getElementById('aud'), interval;
document.getElementById('btn').onclick = turnOff;
function turnOff(){
    if(audio && !audio.paused){
        interval = setInterval(function(){
            console.log('audio volume: ', audio.volume);
            if(!audio || audio.paused || audio.volume < 0.1){
                clearInterval(interval);
            }else{
                audio.volume -= .05; // change this value as per your liking
            }
        }, 200); // change this value as per your liking
    }
}

我想更好的方法可能是使用web-audio

Fiddle Demo