使用gainNode改变音频播放音量实例页面
回到相关文章 »效果:
原始音频
//zxx: 原始音频音量较大,播放前请注意周围环境
音量20%
代码:
HTML代码:
<h4>原始音频</h4> <audio src="./bgmusic.mp3" controls></audio> <h4>音量20%</h4> <button id="button">播放</button>
JS代码:
// 定义一个AudioContext对象
// 因为 Web Audio API都是源自此对象
const audioContext = new AudioContext();
// 创建一个gainNode对象
// gainNode可以对音频输出进行一些控制
const gainNode = audioContext.createGain();
// 音量设置为20%
gainNode.gain.value = 0.2;
// 这个很有必要,建立联系
gainNode.connect(audioContext.destination);
// 创建AudioBufferSourceNode
let source = audioContext.createBufferSource();
// 获取音频资源
fetch('./bgmusic.mp3')
.then(res => res.arrayBuffer())
.then(buffer => audioContext.decodeAudioData(buffer))
.then(audioBuffer => {
source.buffer = audioBuffer;
source.connect(gainNode);
});
// 点击按钮播放
button.onclick = function () {
if (this.textContent == '播放') {
source.start(0);
this.textContent = '暂停';
} else {
const buffer = source.buffer;
// 停止播放
source.stop(0);
this.textContent = '播放';
// stop会销毁数据,所以再次赋值
source = audioContext.createBufferSource();
source.buffer = buffer;
source.connect(gainNode);
}
};