vue播放amr格式音频

这篇博客介绍了如何利用benz-amr-recorder这个npm包,在浏览器环境中将MP3或OGG等音频格式转换为AMR格式,并进行播放。通过示例代码展示了如何导入、初始化和使用该组件,以及处理播放和停止操作。注意解决跨域问题以确保正常播放。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

安装

该插件支持将浏览器 <audio> 所支持的音频格式(例如 MP3 或 OGG 音频)转换成 AMR 音频。

npm i benz-amr-recorder --save

引入

import BenzAMRRecorder from "benz-amr-recorder";

使用(组件可直接复制粘贴使用)

<template>
  <div class="myaudio">
    <span @click="openRecording">{{ msg }}</span>
  </div>
</template>

<script>
import BenzAMRRecorder from "benz-amr-recorder";
export default {
  props: {
    audioUrl: {
      type: String,
      required: true,
    },
  },
  name: "VueAudio",
  data() {
    return {
      amr: null, //播放对象
      msg: "点击播放",
    };
  },
  methods: {
    //播放语音
    openRecording() {
      if (this.amr !== null) {
        this.stopPlayVoice();
      }
      this.amr = new BenzAMRRecorder(); //建立
      console.log(this.amr);
      //⚠️注意跨域问题
      this.amr
        .initWithUrl(this.audioUrl) //初始化
        .then(() => {
          this.amr.play(); //播放
          this.msg = "点击暂停";
          this.amr.onEnded(() => {
            this.msg = "点击播放";
          });
        })
        .catch((e) => {
          this.msg = "点击播放";
          this.$message.error("播放录音失败");
        });
    },
    //停止播放
    stopPlayVoice() {
      if (this.amr.isPlaying()) {
        this.amr.stop();
        this.msg = "点击播放";
      }
    },
  },
};
</script> 
<style lang="scss" scoped>
.myaudio {
  span {
    color: #409eff;
  }
  span:hover {
    cursor: pointer;
  }
}
</style>

 更多使用参考benz-amr-recorder - npm

Vue项目中播放AMR音频文件,可以使用一些JavaScript库来实现音频的解码播放,因为AMR格式不是标准的音频格式,如mp3或wav,它需要特定的解码器。一个常用的库是`@shanet/amr-wasm`,它使用WebAssembly来解码AMR音频文件。 以下是在Vue项目中播放AMR音频的基本步骤: 1. 安装`@shanet/amr-wasm`依赖。 ``` npm install --save @shanet/amr-wasm ``` 2. 在Vue组件中引入该库,并在`mounted`钩子中初始化AMR解码器。 ```javascript import AMR from '@shanet/amr-wasm'; export default { mounted() { AMR().then(AMRDecoder => { const decoder = new AMRDecoder(); this.decodeAMRFile(decoder, 'path/to/your/audio.amr'); }); }, methods: { decodeAMRFile(decoder, path) { fetch(path) .then(response => response.arrayBuffer()) .then(arrayBuffer => { const samples = decoder.decode(arrayBuffer); // 使用Web Audio API播放解码后的音频 const audioContext = new AudioContext(); const source = audioContext.createBufferSource(); source.buffer = audioContext.createBuffer(1, samples.length / 2, 8000); source.buffer.getChannelData(0).set(samples); source.connect(audioContext.destination); source.start(); }) .catch(error => console.error('AMR decoding error:', error)); } } } ``` 3. 在模板中添加一个音频播放器元素(例如`<audio>`标签),虽然在这个例子中我们使用Web Audio API来控制音频播放,但如果你想要使用HTML5的`<audio>`标签来播放,你需要将AMR文件转换为浏览器支持的格式,如mp3。 请注意,这段代码仅提供了一个基本的实现思路,实际项目中可能需要处理更多的细节,例如错误处理、音频播放控制等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值