2011-10-29 56 views
2

音頻元素玩弄容積量:JavaScript的慢慢減少音頻元素

audio.setVolume(.20) 

在某一點上我想淡出音量,而不是有它突然中斷,所以在本質上我想

audio.setVolume(.15) 
audio.setVolume(.10) 
audio.setVolume(.05) 
audio.setVolume(.03) 
audio.setVolume(.01) 

但這些變化之間需要一些非常短暫的延遲,以便它們可以聽到,並且我可以淡入淡出效果。什麼是正確的方法來做到這一點?

謝謝!

+0

你應該看看[setTimeout()或setInterval()](http://stackoverflow.com/questions/758688/sleep-in-javascript)。 – ObscureRobot

回答

7

你可以使用一個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); 
6

我會敷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'); 
}); 

一旦淡入​​淡出完成,它將觸發一個回調,您可以使用它來播放下一首歌曲。

0

您也可以使用此鼠標鍵事件。

audio.on('keydown', function() { 
// and here keep increasing or decreasing the volume, untill keyUp 
}) 

由於被查看,它的jQuery!你可以用它來做你的工作。此外,音頻標籤是爲div,包含音頻標籤!