代码如下:
// HTML5 Canvas 动态波形生成器
// 使用JS读取波形文件并生成动态波形
// 创建Canvas并设置上下文
const canvas = document.createElement('canvas');
canvas.width = 800;
canvas.height = 400;
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
// 波形数据
let waveform = [];
// 加载波形文件数据
async function loadWaveformData(url) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const arrayBuffer = await response.arrayBuffer();
const audioContext = new AudioContext();
const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);
waveform = audioBuffer.getChannelData(0); // 获取左声道数据
console.log('Waveform data loaded:', waveform);
drawWaveform();
} catch (error) {
console.error('Error loading waveform data:', error);
}
}
// 动态波形绘制参数
const waveParams = {
sampleRate: 800, // 每帧波形的采样点数
offset: 0, // 动态偏移
speed: 2 // 波形滚动速度
};
// 动态绘制波形
function drawWaveform() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
const step = Math.max(1, Math.floor(waveform.length / waveParams.sampleRate)); // 每步采样间隔
const centerY = canvas.height / 2;
for (let i = 0; i < canvas.width; i++) {
const sampleIndex = (waveParams.offset + i * step) % waveform.length;
const sampleValue = waveform[Math.floor(sampleIndex)];
const y = centerY + sampleValue * centerY; // 将样本值映射到画布高度
if (i === 0) {
ctx.moveTo(i, y);
} else {
ctx.lineTo(i, y);
}
}
ctx.strokeStyle = '#007BFF';
ctx.lineWidth = 2;
ctx.stroke();
waveParams.offset += waveParams.speed; // 波形滚动
requestAnimationFrame(drawWaveform);
}
// 加载波形文件(将 `example.wav` 替换为你的文件路径)
loadWaveformData('example.wav');