【音频可视化】通过canvas绘制音频波形图

前言

这两天写项目刚好遇到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);
  });
};
相关推荐
We་ct几秒前
深度剖析浏览器跨域问题
开发语言·前端·浏览器·跨域·cors·同源·浏览器跨域
weixin_4277716125 分钟前
前端调试隐藏元素
前端
爱上好庆祝1 小时前
学习js的第五天
前端·css·学习·html·css3·js
C澒2 小时前
IntelliPro 产研协作平台:基于 AI Agent 的低代码智能化配置方案设计与实现
前端·低代码·ai编程
一袋米扛几楼982 小时前
【Git】规范化协作:详解 GitHub 工作流中的 Issue、Branch 与 Pull Request 最佳实践
前端·git·github·issue
网络点点滴2 小时前
前端与后端的区别与联系
前端
EnCi Zheng2 小时前
M5-markconv自定义CSS样式指南 [特殊字符]
前端·css·python
kyriewen2 小时前
你的网页慢,用户不说直接走——前端性能监控教你“读心术”
前端·性能优化·监控
广州华水科技2 小时前
北斗GNSS变形监测在大坝安全监测中的应用与优势分析
前端
前端老石人3 小时前
前端开发中的 URL 完全指南
开发语言·前端·javascript·css·html