js 实现音频
使用 Web Audio API 播放音频
通过 AudioContext 和 fetch 加载音频文件并播放:
const audioContext = new (window.AudioContext || window.webkitAudioContext)();
fetch('audio.mp3')
.then(response => response.arrayBuffer())
.then(buffer => audioContext.decodeAudioData(buffer))
.then(decodedData => {
const source = audioContext.createBufferSource();
source.buffer = decodedData;
source.connect(audioContext.destination);
source.start();
});
使用 HTML5 <audio> 标签
直接在 HTML 中嵌入音频控件,通过 JavaScript 控制播放:
<audio id="myAudio" src="audio.mp3"></audio>
<script>
const audio = document.getElementById('myAudio');
audio.play(); // 播放
audio.pause(); // 暂停
audio.currentTime = 0; // 重置进度
</script>
动态生成音频(Oscillator)
使用 AudioContext 生成简单音调:
const ctx = new AudioContext();
const oscillator = ctx.createOscillator();
oscillator.type = 'sine'; // 波形类型:sine, square, sawtooth, triangle
oscillator.frequency.value = 440; // 频率(Hz)
oscillator.connect(ctx.destination);
oscillator.start();
oscillator.stop(ctx.currentTime + 2); // 2秒后停止
音频可视化(AnalyserNode)
结合 Canvas 实现音频频谱可视化:

const audioCtx = new AudioContext();
const analyser = audioCtx.createAnalyser();
const source = audioCtx.createMediaElementSource(document.getElementById('myAudio'));
source.connect(analyser);
analyser.connect(audioCtx.destination);
const bufferLength = analyser.frequencyBinCount;
const dataArray = new Uint8Array(bufferLength);
analyser.getByteFrequencyData(dataArray);
// 使用 Canvas 绘制频谱(需循环调用)
function draw() {
requestAnimationFrame(draw);
analyser.getByteFrequencyData(dataArray);
// 绘制逻辑...
}
注意事项
- 跨浏览器兼容性:部分旧浏览器需使用
webkit前缀(如webkitAudioContext)。 - 用户交互限制:现代浏览器要求音频播放必须由用户手势(如点击)触发。
- 格式支持:常见音频格式为 MP3、WAV、OGG,需根据浏览器兼容性选择。






