用javascript实现HTML5 播放音乐的淡出效果

最近在做一个东西,呵呵,暂时保密。里面用到了html5播放音乐,但是我想在一定的时候使用淡出效果关闭音乐。
几经查找,终于找到了解决办法,代码如下:
html部分

<audio preload="auto" id="music">
            <source src="music.mp3" />
        </audio>

js部分

function FadeOut() {
    var music = document.getElementById('music');
    audioElement = music;
    $(audioElement).on('timeupdate', function() {               
        var vol = 1,
        interval = 200; // 200ms interval
        if (audioElement.volume == 1) {
            var intervalID = 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;
                // limit to 2 decimal places
                    // also converts to string, works ok
                    audioElement.volume = vol.toFixed(2);
            } else {
                // Stop the setInterval when 0 is reached
                clearInterval(intervalID);
            }
            }, interval);
        }
    });
}

如果需要淡入效果,也可以参考一下

2013-05-17 14:13222javascript淡出html5audio