---
title: "用javascript实现html5 播放音乐的淡出效果"
url: "https://lerry.me/post/2013/05/html-audio-fadeout"
date: 2013-05-17T06:13:00.000Z
updated: 2026-08-22T13:49:39.165Z
tags:
  - "JavaScript"
  - "HTML5"
language: zh-CN
---

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

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

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

js部分  

```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);  
        }  
    });  
}  
```  

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