前言
这两天写项目刚好遇到Ai对话相关的需求,需要录音功能,绘制录制波形图,写了一个函数用canvas
实现可视化,保留分享一下,有需要的直接粘贴即可,使用时传入一个1024
长的,0-255
大小的Uint8Array
类型音频数据源
javascript
<canvas ref="canvasRef" width="800" height="200"></canvas>
javascript
const drawWaveform = (audioArray) => {
const canvas = canvasRef.value;
if (!canvas || !audioArray) return;
const ctx = canvas.getContext('2d');
if (!ctx) return;
const width = canvas.width;
const height = canvas.height;
const bufferLength = audioArray.length;
// 清除画布
ctx.clearRect(0, 0, width, height);
// 设置线条样式
ctx.strokeStyle = '#4f35b5';
ctx.lineWidth = 2;
ctx.beginPath();
const sliceWidth = width / bufferLength;
let x = 0;
for (let i = 0; i < bufferLength; i++) {
const value = audioArray[i] / 255.0; // 将0-255的值归一化为0-1
const y = value * height;
if (i === 0) {
ctx.moveTo(x, y);
} else {
ctx.lineTo(x, y);
}
x += sliceWidth;
}
ctx.stroke();
};
通过requestAnimationFrame
调用即可
示例:
javascript
// 持续更新波形
const updateWaveform = () => {
ensureRecorder(() => {
audioArray.value = recorder!.getRecordAnalyseData();
drawWaveform(audioArray.value);
animationFrameId = requestAnimationFrame(updateWaveform);
});
};