vue录音实现

<template>
  <div>
    <div>
      <button @click="startRecording">开始录音</button>
      <button @click="stopRecording">停止录音</button>
      <button @click="bofang">播放</button>
      <audio ref="audioPlayer"></audio>
    </div>
  </div>
</template>

<script>
// import lamejs from 'lamejs';
import * as qiniu from "qiniu-js";
import axios from "axios";
export default {
  data() {
    return {
      isRecording: false,
      stream: null,
      recorder: null,
      chunks: [],
      audioUrl: null,
      num: 0,
      timer: 'null',
      blob: null,
    };
  },
  beforeDestroy() {
    // 组件销毁前释放资源
    if (this.audioUrl) {
      URL.revokeObjectURL(this.audioUrl);
    }
  },
  methods: {
    async startRecording() {
      if (this.isRecording) {
        return; // 已经在录音了,不需要再次开始
      }
      this.timer = setInterval(() => {
        this.num++
      }, 1000)
      this.chunks = []
      this.isRecording = true;
      this.stream = await navigator.mediaDevices.getUserMedia({ audio: true });
      this.recorder = new MediaRecorder(this.stream);
      this.recorder.addEventListener('dataavailable', event => {
        console.log(event, 'event');
        this.chunks.push(event.data);
        this.blob = new Blob(this.chunks, { type: 'audio/mp3' });
      });
      this.recorder.start();
    },
    stopRecording() {
      if (!this.isRecording) {
        alert('没有在录音,不需要停止')
        return; // 没有在录音,不需要停止
      }
      clearInterval(this.timer)
      this.isRecording = false;
      this.recorder.stop();
      this.stream.getTracks().forEach(track => track.stop());
      // 将录制的音频数据转换为Blob对象
      // let localUrl = (window.URL || window.webkitURL).createObjectURL(this.blob)
      // localUrl = localUrl.substr(27)
      console.log(this.blob, 888);
      // console.log(localUrl, 8888);
      console.log(this.chunks);
      console.log(URL.createObjectURL(this.blob));
      // if (this.audioUrl) {
      //   URL.revokeObjectURL(this.audioUrl);
      // }
      // 使用七牛云SDK进行文件上传
      axios.get('*********************').then(res => {
        const token = res.data.Result.UploadToken;
        const key = 'vvchat.app/' + new Date().getTime(); // 上传后在七牛云上的文件名
        const config = {
          useCdnDomain: true,
          region: qiniu.region.as0
        };
        const putExtra = {
          mimeType: 'audio/mp3'
        };
        const observable = qiniu.upload(this.blob, key, token, putExtra, config);
        observable.subscribe({
          next(res) {
            // 上传进度回调
            console.log('上传进度:', res.total.percent);
          },
          error(err) {
            // 上传失败回调
            console.error('上传失败:', err);
          },
          complete(res) {
            // 上传完成回调
            console.log('上传成功:', res);
          }
        });
      })
    },
    bofang() {
      this.$refs.audioPlayer.src = URL.createObjectURL(this.blob);
      this.$refs.audioPlayer.play();
    }
  }
};
</script>

  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Vue实现录音功能,可以考虑使用Web API中的MediaRecorder和getUserMedia方法。这些API允许您访问用户的麦克风并将音频数据录制到文件中。 以下是一个简单的Vue示例,演示如何实现录音功能: 1.首先,您需要在Vue组件中引入MediaRecorder和getUserMedia: ```javascript import { getUserMedia } from 'webrtc-adapter'; import MediaRecorder from 'audio-recorder-polyfill'; ``` 2.在Vue组件的data属性中添加一个名为“recording”的布尔值,用于跟踪录音状态: ```javascript data() { return { recording: false } } ``` 3.在Vue组件的methods属性中添加一个名为“startRecording”的方法,用于开始录音: ```javascript methods: { startRecording() { this.recording = true; const constraints = { audio: true }; navigator.mediaDevices.getUserMedia(constraints) .then(stream => { const options = { mimeType: 'audio/webm' }; const mediaRecorder = new MediaRecorder(stream, options); mediaRecorder.start(); mediaRecorder.ondataavailable = event => { const audioFile = new File([event.data], 'recording.webm'); // Do something with the audio file, e.g. upload it to a server }; this.mediaRecorder = mediaRecorder; }) .catch(error => { console.error('Error accessing user media:', error); }); } } ``` 4.在Vue组件的template中添加一个按钮来启动录音: ```html <template> <div> <button v-if="!recording" @click="startRecording">Start Recording</button> <button v-else @click="stopRecording">Stop Recording</button> </div> </template> ``` 5.添加一个名为“stopRecording”的方法,用于停止录音: ```javascript stopRecording() { this.recording = false; this.mediaRecorder.stop(); } ``` 这就是如何在Vue实现录音功能的简单示例。请注意,此示例中使用的MediaRecorder和getUserMedia API可能需要polyfill来确保与所有浏览器兼容。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值