HTML代码:
<button id="button">点击播放</button>
JS代码:
const url = './htmlbook.wav';
// 点击按钮,音频淡入淡出播放
button.onclick = function () {
// 请求数据
fetch(url).then(res => res.arrayBuffer()).then(buffer => {
const audioContext = new AudioContext();
audioContext.decodeAudioData(buffer, function (audioBuffer) {
const source = audioContext.createBufferSource();
const gainNode = audioContext.createGain();
// 起始音量静音
gainNode.gain.value = 0;
gainNode.connect(audioContext.destination);
// buffer数据设置
source.buffer = audioBuffer;
source.connect(gainNode);
source.start();
gainNode.gain.linearRampToValueAtTime(1.0, audioContext.currentTime + 1);
// 时长计算
const duration = audioBuffer.duration;
setTimeout(() => {
gainNode.gain.linearRampToValueAtTime(0.01, audioContext.currentTime + 1);
}, duration * 1000 - 1200);
});
});
}