html使用wavesurfer.js把audio文件改成可视化音波音频

audio效果

使用wavesurfer.js做成可视化音波音频

首先要先下载好wavesurfer.js依赖

npm install wavesurfer.js --save
或者
yarn add wavesurfer.js

下载完之后,考虑到直接使用在现有的页面上,会显得代码很多,而且无法复用,这里直接做成一个工具类,给大家参考使用

<template>
  <div v-if="audioUrl && audioUrl !== ''" style="width: 100%">
    <a-spin :spinning="loading"></a-spin>
    <div ref="waveform"></div>
    <div ref="timeline"></div>
    <input type="range" v-model="currentTime" :max="duration" @input="seek" style="width: 100%">
    <button @click="playPause">{{ isPlaying ? '暂停' : '播放' }}</button>
  </div>
</template>

<script>
import WaveSurfer from 'wavesurfer.js';
import TimelinePlugin from 'wavesurfer.js/dist/plugins/timeline.esm.js';

export default {
  name: 'WaveSurferTool',
  props: {
    audioUrl: {
      type: String,
      required: true
    },
    waveColor: {
      type: String,
      default: 'violet'
    },
    progressColor: {
      type: String,
      default: 'purple'
    }
  },
  data() {
    return {
      waveSurfer: null,
      loading: true,
      isPlaying: false,
      currentTime: 0,
      duration: 0
    }
  },
  mounted() {
    let that = this;
    this.waveSurfer = WaveSurfer.create({
      container: this.$refs.waveform,
      waveColor: this.waveColor,
      progressColor: this.progressColor,
      width: '912px',
      plugins: [
        TimelinePlugin.create({
          container: this.$refs.timeline,
          height: 20,
          timeInterval: 5,
          primaryLabelInterval: 5,
          secondaryLabelInterval: 1,
          style: {
            fontSize: '14px', // 调整字体大小
            lineHeight: '1.2', // 调整行高
            color: '#2D5B88'
          }
        })
      ],
      url: this.audioUrl
    });
    this.waveSurfer.on('ready', function () {
      console.log('初始化结束');
      that.loading = false;
      that.duration = that.waveSurfer.getDuration();
    });

    this.waveSurfer.on('click', () => {
      this.playPause();
    });

    this.waveSurfer.on('audioprocess', () => {
      this.currentTime = this.waveSurfer.getCurrentTime();
    });
  },
  beforeDestroy() {
    if (this.waveSurfer) {
      this.waveSurfer.destroy();
    }
  },
  methods: {
    playPause() {
      if (this.isPlaying) {
        this.waveSurfer.pause();
      } else {
        this.waveSurfer.play();
      }
      this.isPlaying = !this.isPlaying;
    },
    seek() {
      this.waveSurfer.seekTo(this.currentTime / this.duration);
    }
  }
}
</script>

具体使用方法,在需要使用转成可视化的地方直接引用即可,:audioUrl对应的路径,做线上的话就要发送http请求才能拿到录音文件!

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值