当前位置: 首页 > article >正文

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

前言

这两天写项目刚好遇到Ai对话相关的需求,需要录音功能,绘制录制波形图,写了一个函数用canvas实现可视化,保留分享一下,有需要的直接粘贴即可,使用时传入一个1024长的,0-255大小的Uint8Array类型音频数据源

<canvas ref="canvasRef" width="800" height="200"></canvas>
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调用即可

示例:

// 持续更新波形
const updateWaveform = () => {
  ensureRecorder(() => {
    audioArray.value = recorder!.getRecordAnalyseData();
    drawWaveform(audioArray.value);
    animationFrameId = requestAnimationFrame(updateWaveform);
  });
};

http://www.kler.cn/news/341022.html

相关文章:

  • 什么是静态加载-前端
  • Mosaic for Mac:让你的Mac窗口管理更智能
  • python发邮件附件:配置SMTP服务器与认证?
  • BKP读写备份寄存器
  • vscode软件中可以安装的一些其他插件
  • YOLO11改进|注意力机制篇|引入矩形自校准模块RCM
  • 案例分享—国外优秀UI设计作品赏析
  • C语言 | Leetcode C语言题解之第467题环绕字符串中唯一的子字符串
  • Wasserstein距离
  • 支持向量机-笔记
  • Ethernet IP 转 Profinet网关在流量计中的应用
  • vmware下ubuntu18.04中使用笔记本的摄像头
  • 传统的机器学习在自然语言处理领域中对比深度学习和大语言模型有哪些优势?
  • 鸿蒙fork()功能
  • Openstack 安装教程
  • 论文阅读(十二):Attention is All You Need
  • 单片机(学习)2024.10.9
  • LeetCode讲解篇之300. 最长递增子序列
  • 【含开题报告+文档+PPT+源码】基于SpringBoot+Vue的新能源停车场管理系统
  • Leetcode 24 Swap Nodes in Pairs