js实现声音
使用 Web Audio API 播放声音
Web Audio API 提供了强大的音频处理能力,适合需要精细控制的场景。
// 创建音频上下文
const audioContext = new (window.AudioContext || window.webkitAudioContext)();
// 加载音频文件
function playSound(url) {
fetch(url)
.then(response => response.arrayBuffer())
.then(arrayBuffer => audioContext.decodeAudioData(arrayBuffer))
.then(audioBuffer => {
const source = audioContext.createBufferSource();
source.buffer = audioBuffer;
source.connect(audioContext.destination);
source.start();
});
}
// 使用示例
playSound('sound.mp3');
使用 HTML5 Audio 元素
对于简单的音频播放需求,HTML5 Audio 元素是最简单的实现方式。

// 创建音频对象
const audio = new Audio('sound.mp3');
// 播放音频
function play() {
audio.play();
}
// 暂停音频
function pause() {
audio.pause();
}
使用第三方库 Howler.js
Howler.js 是一个流行的音频库,简化了跨浏览器的音频处理。
// 引入 Howler.js 后
const sound = new Howl({
src: ['sound.mp3']
});
// 播放
sound.play();
// 暂停
sound.pause();
实现声音可视化
结合 Canvas 和 Web Audio API 可以实现声音波形可视化。

const audioContext = new AudioContext();
const analyser = audioContext.createAnalyser();
const canvas = document.getElementById('visualizer');
const ctx = canvas.getContext('2d');
// 连接音频源到分析器
function setupAudio(src) {
const audio = new Audio(src);
const source = audioContext.createMediaElementSource(audio);
source.connect(analyser);
analyser.connect(audioContext.destination);
audio.play();
// 绘制波形
function draw() {
requestAnimationFrame(draw);
const bufferLength = analyser.frequencyBinCount;
const dataArray = new Uint8Array(bufferLength);
analyser.getByteTimeDomainData(dataArray);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.lineWidth = 2;
ctx.strokeStyle = 'rgb(0, 0, 0)';
ctx.beginPath();
const sliceWidth = canvas.width / bufferLength;
let x = 0;
for(let i = 0; i < bufferLength; i++) {
const v = dataArray[i] / 128.0;
const y = v * canvas.height/2;
if(i === 0) {
ctx.moveTo(x, y);
} else {
ctx.lineTo(x, y);
}
x += sliceWidth;
}
ctx.lineTo(canvas.width, canvas.height/2);
ctx.stroke();
}
draw();
}
处理移动端自动播放限制
移动端浏览器通常阻止自动播放,需要用户交互后解锁音频。
document.body.addEventListener('click', function() {
const audioContext = new AudioContext();
// 现在可以播放音频
}, { once: true });
音频格式兼容性处理
不同浏览器支持的音频格式不同,可以提供多种格式源。
const audio = new Audio();
audio.src = 'sound.ogg';
audio.type = 'audio/ogg';
// 如果不支持ogg,回退到mp3
audio.addEventListener('error', function() {
audio.src = 'sound.mp3';
audio.type = 'audio/mpeg';
audio.play();
});






