audio音频可视化

<canvas id="canvas" style="width:100%;height:600px;"></canvas>
<audio id="audio" :src="audioSrc" autoplay controls controlslist="nodownload" @play="onplay" @pause='onPause' @ended="overAudio"></audio>

let config = {
  URL: '',
  timeout: 3000,
  headers: {'content-Type': '', 'token': ''}
  responseType: 'arraybuffer',
  params: ''
}

axios.get('', config).then((data) => {
   const blob = new Blob([data])
   audioSrc = window.URL.createObjectURL(blob) 
   const AudioContext = window.AudioContext || window.webkitAudioContext;
   const audio = new AudioContext();
   let analyser = audio.createAnalyser();
   analyser.fftSize = 256; //设置傅里叶系数
   let source = audio.createBufferSource();
   audio.decodeAudioData(data, function (buffer) {
   // 将解码后得到的值赋给buffer
   source.buffer = buffer;
   // 音频==》分析器==》扬声器
   source.connect(analyser);
   analyser.connect(audio.destination);
  });
  this.$nextTick(() => {
      const canvas = document.getElementById("canvas");
      const cxt = canvas.getContext("2d");
      const WIDTH = canvas.width;
      const HEIGHT = canvas.height;
      const lineWidth = 4;
      const gap = 6;
      const maxNum = Math.round(WIDTH / (lineWidth + gap));
      cxt.strokeStyle = "red";
      cxt.lineCap = "round";
      cxt.lineWidth = lineWidth;
      const that = this;
      onplay()
      function render() {
        cxt.clearRect(0, 0, WIDTH, HEIGHT); //清空画布
        //that.analyser.frequencyBinCount是fftSize的一半
        const dataArray = new Uint8Array(that.analyser.frequencyBinCount);
        that.analyser.getByteFrequencyData(dataArray); //获取音频字节流
        for (let i = 0; i < maxNum; i++) {
          cxt.strokeStyle = "#008b8b";
          const value = Math.round((dataArray[i] / 128) * 20);
          cxt.beginPath();
          cxt.moveTo(i * (lineWidth + gap) + gap / 2, HEIGHT / 2);
          cxt.lineTo(i * (lineWidth + gap) + gap / 2, HEIGHT / 2 - value - 2);
          cxt.stroke();
          cxt.beginPath();
          cxt.moveTo(i * (lineWidth + gap) + gap / 2, HEIGHT / 2);
          cxt.lineTo(i * (lineWidth + gap) + gap / 2, HEIGHT / 2 + value + 2);
          cxt.stroke();
        }
        //递归调用渲染
        window.requestAnimationFrame(render);
      }
      // requestAnimationFrame()用来渲染动画帧,此时渲染第一帧
      window.requestAnimationFrame(render); 
   })
})
// 开始
function onplay() {
    let startTime = that.audio.currentTime;
    that.source.start(0, startTime);  
}
// 暂停
function onPause () {

}
// 结束
function overAudio () {

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值