首页 > 其他分享 >Vue 前端页面利用MediaRecorder实现音频录制

Vue 前端页面利用MediaRecorder实现音频录制

时间:2024-06-05 09:25:15浏览次数:16  
标签:audioRecorder MediaRecorder isPlay 音频 录音 Vue null isRecording audio

Don't Talk, code is here:

重点是startRecord 方法

<template>
  <div>
    <el-tooltip class="item" effect="dark" content="再次点击 【开始录音】 即为重新录制,之前录制的将被作废" placement="top">
      <el-button :disabled="isPlay" :icon="isRecording?'el-icon-turn-off-microphone  el-icon--right' : 'el-icon-microphone el-icon--right'" plain :type="isRecording ? 'danger' : 'primary'" size="mini" @click="togleAudioRecord">{{ isRecording ? '停止录音' : '开始录音' }}</el-button>
    </el-tooltip>
    <el-button plain :disabled="isRecording" type="info" size="mini" @click="toglePlayRecord">
      <svg-icon :icon-class="isPlay ? 'stop-white' :'play-fill-white' " />{{ isPlay ? '停止播放' : '试听录音' }}
    </el-button>
    <el-button icon="el-icon-upload el-icon--right" plain type="success" size="mini" @click="uploadRecord">上传</el-button>
    <span :class="{ 'time-black': isPlay, 'time-red': isRecording && recordingSecond %2 === 0, 'time-pink': isRecording && recordingSecond %2 === 1 }" class="font-bold margin-horizon-10">{{ formatTimeFormSec(recordingSecond) }}</span>
    <audio ref="audio" :volume="0.85" @ended="audioPlayEnd" />
  </div>
</template>

<script>
export default {
  name: 'AudioRecorder',
  data() {
    return {
      isRecording: false,
      recordingSecond: 0,
      intervalSeed: null,
      isPlay: false,
      audioStream: null, // 用户存储媒体流
      audioRecorder: null, // 录音对象
      audioBlob: null, // 录音文件
      audioUrl: null // 录音文件试听url
    }
  },
  beforeDestroy() { // 组件销毁时,停止当前正在执行的操作,释放资源,防止内存泄漏
    // 如果正在录制,则结束录制
    this.isRecording && this.stopRecord()
    // 如果正在播放,则停止播放
    this.isPlay && this.stop()
  },
  methods: {
    togleAudioRecord() {
      this.isRecording = !this.isRecording
      if (this.isRecording) { // 需要开始录音
        this.startRecord()
        this.startInterval() // 录音时长计时器
      } else { // 需要结束录音
        this.stopRecord()
        this.stopInterval()
      }
    },
    toglePlayRecord() {
      if (this.audioUrl == null) {
        this.$message.error('请先录制音频')
        return
      }
      this.isPlay = !this.isPlay
      if (this.isPlay) { // 需要播放
        this.play()
        this.startInterval() // 录音时长计时器
      } else { // 停止播放
        this.stop()
        this.stopInterval()
      }
    },
    uploadRecord() { // TODO 上传录音

    },
    audioPlayEnd() { // 音频播放结束将被调用
      this.isPlay = false
      this.stopInterval()
    },
    startRecord() { // 开始录音
      navigator.mediaDevices.getUserMedia({ audio: true, video: false })
        .then(stream => {
          this.audioStream = stream
          this.audioRecorder = new MediaRecorder(stream)
          this.audioRecorder.start()
          this.audioRecorder.ondataavailable = e => {
            this.audioBlob = new Blob([e.data], { type: 'audio/wav' })
            this.audioUrl = URL.createObjectURL(this.audioBlob)
            this.$refs.audio.src = this.audioUrl
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    stopRecord() { // 结束录音
      this.audioRecorder.stop()
      this.audioStream.getTracks().forEach(track => track.stop())
      this.audioRecorder = null
      this.audioStream = null
      this.audioBlob = null
      this.audioUrl = null
    },
    play() { // 开始播放
      this.$refs.audio.play()
    },
    stop() { // 停止播放
      this.$refs.audio.currentTime = 0
      this.$refs.audio.pause()
    },
    formatTimeFormSec(sec) { // 将录制的秒数转换为 00:01:01 格式的字符串
      const h = Math.floor(sec / 3600)
      const m = Math.floor(sec % 3600 / 60)
      const s = Math.floor(sec % 60)
      return (h > 9 ? h : '0' + h) + ':' + (m > 9 ? m : '0' + m) + ':' + (s > 9 ? s : '0' + s)
    },
    startInterval() { // 开始计时秒数
      this.recordingSecond = 0
      this.intervalSeed = setInterval(() => {
        this.recordingSecond++
      }, 1000)
    },
    stopInterval() { // 停止计时秒数
      clearInterval(this.intervalSeed)
    } }
}
</script>

<style lang="scss" scoped>
.time-black{
  color: #303133;
}

.time-red{
  color: #ff0000;
}

.time-pink{
  color: #ff6767;
}

.font-bold{
  font-weight: bolder;
}

.margin-horizon-10{
  margin: 0 10px;
}
</style>

环境

  1. Vue 2.?
  2. Element-ui
  3. Ruoyi-vue

备注

代码是完整的组件,放在

      <el-form-item label="录音">
        <AudioRecorder />
      </el-form-item>

显示起来刚刚好。

标签:audioRecorder,MediaRecorder,isPlay,音频,录音,Vue,null,isRecording,audio
From: https://www.cnblogs.com/echo-lovely/p/18232248

相关文章

  • Vue前端实现接收rabbitMQ及时消息 原
    https://blog.csdn.net/dawnStart/article/details/110479833打开APPVue前端实现接收rabbitMQ及时消息原创2020-12-0214:03:11阅读量1.4wAI必读dawnStart码龄4年关注Vue前端实现实时接收rabbitMQ及时消息,看了别人写的不太详细1.rabbitMQ安装Stom插件2.Vu......
  • Vue3-shallowRef与shallowReactive
    shallowRef作用:创建一个响应式数据,但只对顶层属性进行响应式处理。用法:letmyVar=shallowRef(initialValue);特点:只跟踪引用值的变化,不关心值内部的属性变化。shallowReactive作用:创建一个浅层响应式对象,只会使对象的最顶层属性变成响应式的,对象内部的嵌套属......
  • Vue3-Pinia状态管理器
    Pinia是Vue的专属状态管理库,它允许你跨组件或页面共享状态。如果你熟悉组合式API的话,你可能会认为可以通过一行简单的 exportconststate=reactive({}) 来共享一个全局状态。对于单页应用来说确实可以,但如果应用在服务器端渲染,这可能会使你的应用暴露出一些安全漏洞......
  • vue后台用户路由权限和按钮权限实现原理
    概论主要是通过一个唯一标识name或者id来过滤判断用户所处的角色是否有路由的权限或者按钮的权限一般路由都有一个一个name可以作为唯一标识一般按钮的话,可以自定义一个name作为标识业务逻辑后台通过选中路由或者按钮给角色,代表这个角色有数组中name[]的权限,用户或者部门再......
  • vue-router 源码分析——2. router-link 组件是如何实现导航的
    这是对vue-router3版本的源码分析。本次分析会按以下方法进行:按官网的使用文档顺序,围绕着某一功能点进行分析。这样不仅能学习优秀的项目源码,更能加深对项目的某个功能是如何实现的理解。这个对自己的技能提升,甚至面试时的回答都非常有帮助。在围绕某个功能展开讲解时,所......
  • 基于SpringBoot+Vue的足球社区管理系统(源码+lw+部署文档+讲解等)
    文章目录前言详细视频演示项目运行截图技术框架后端采用SpringBoot框架前端框架Vue可行性分析系统测试系统测试的目的系统功能测试数据库表设计代码参考数据库脚本为什么选择我?获取源码前言......
  • 基于SpringBoot+Vue的医院住院管理系统设计与实现(源码+lw+部署文档+讲解等)
    文章目录前言详细视频演示项目运行截图技术框架后端采用SpringBoot框架前端框架Vue可行性分析系统测试系统测试的目的系统功能测试数据库表设计代码参考数据库脚本为什么选择我?获取源码前言......
  • Vue3单文件组件实现省市区县三级联动
    Provinces.vue<template>  <divclass="select-container">    <selectv-model="selectedProvince"@change="handleProvinceChange">      <optionvalue=""disabled>请选择省份</opti......
  • 基于springboot-vue的毕业论文管理系统(11728)
     有需要的同学,源代码和配套文档领取,加文章最下方的名片哦一、项目演示二、资料项目演示视频介绍完整源代码(前后端源代码+SQL脚本)配套文档(LW+PPT+开题报告)远程调试控屏包运行三、技术介绍Java语言SSM框架SpringBoot框架Vue框架JSP页面Mysql数据库IDEA/Eclipse开发四、项......
  • springboot+vue+mybatis学生奖惩管理系统+PPT+论文+讲解+售后
    在如今社会上,关于信息上面的处理,没有任何一个企业或者个人会忽视,如何让信息急速传递,并且归档储存查询,采用之前的纸张记录模式已经不符合当前使用要求了。所以,对学生奖惩信息管理的提升,也为了对学生奖惩信息进行更好的维护,学生奖惩管理系统的出现就变得水到渠成不可缺少。通过对......