js + canvas实现音频可视化

效果图:

 

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<style>
  * {
    padding: 0;
    margin: 0;
    background-color: #000;
    text-align: center;
  }
  canvas {
    border-bottom: 1px solid skyblue;
  }
</style>
<body>
  <canvas></canvas>
  <audio 
    crossorigin="anonymous"
    src="./M500004bfQ2t3H8Cn0.mp3" controls></audio>

  <script>
    const audio = document.querySelector('audio')
    const cvs = document.querySelector('canvas')
    const ctx = cvs.getContext('2d')
    // 初始化 canvas 尺寸
    function initCvs() {
      cvs.width = (window.innerWidth / 2) * devicePixelRatio
      cvs.height = (window.innerHeight / 2) * devicePixelRatio
    }
    initCvs()

    let isInit = false
    let dataArray, analyser
    audio.onplay = function () {
      if(isInit) {
        return
      }

      // 初始化
      const audioCtx = new AudioContext()   // 创建音频上下文
      const source = audioCtx.createMediaElementSource(audio)  // 创建音频源节点
      
      analyser = audioCtx.createAnalyser()   // 创建分析器
      analyser.fftSize = 512  // 设置分析器的 fft 大小
      // // // 创建数组,用于接受分析器的数据
      dataArray = new Uint8Array(analyser.frequencyBinCount) 
      source.connect(analyser)  // 连接分析器 
      analyser.connect(audioCtx.destination)  // 连接音频上下文和分析器

      isInit = true
    }

    audio.onpause = () => {
      isInit = false
    }

    function draw() {
      requestAnimationFrame(draw)
      
      // 清空画布
      const { width, height} = cvs
      ctx.clearRect(0, 0, width, height)
      if(!isInit) {
        return
      }

      // 从分析器节点分析出数据到数组中
      analyser.getByteFrequencyData(dataArray)

      const len = dataArray.length / 2.5
      // 每个柱子的宽度
      const barWidth = width / len / 2
      for (let i = 0; i < len; i++) {
        const data = dataArray[i] // <256
        const barHeight = data / 250 * height
        // 二个 x 点画出对称图形
        const x1 = i * barWidth + width / 2
        const x2 = width / 2 - (i + 1) * barWidth
        const y = height - barHeight
        ctx.fillStyle = '#78C5F7'
        ctx.fillRect(x1, y, barWidth - 2, barHeight)
        ctx.fillRect(x2, y, barWidth - 2, barHeight)
        
      }
      console.log(dataArray);

    }

    draw()
  </script>
</body>
</html>
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@前端小菜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值