1、代码
首先安装依赖包:recorderx
npm install recorderx -S
<template><div class="container"><div class="mt-30"><el-button @click="onStartRecord">开始录音</el-button><el-button @click="onStopRecord">停止录音</el-button></div></div> </template><script> export default {name: "home", }; </script> <script setup> import { reactive, ref, computed, watch, toRaw, onMounted } from "vue"; import moment from "moment"; import Recorder, { ENCODE_TYPE } from "recorderx";let recorder;const recordName = ref(""); function onStartRecord() {console.log("开始录音");recorder = new Recorder(true);recorder.start().then(() => {console.log("start recording");}).catch((error) => {console.log("Recording failed.", error);}); }function onStopRecord() {console.log("停止录音");recorder.pause();let wav = recorder.getRecord({ encodeTo: ENCODE_TYPE.WAV });console.log("wav", wav); const aLink = document.createElement("a");const blob = wav; // new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });aLink.style.display = "none";aLink.href = URL.createObjectURL(blob);recordName.value = moment().format("YYYYMMDDHHmmss") + ".mp3";aLink.setAttribute("download", recordName.value); // 设置下载文件名称 document.body.appendChild(aLink);aLink.click();URL.revokeObjectURL(aLink.href); // 清除引用 document.body.removeChild(aLink); } </script>
2、效果
停止录音后,文件会自动保存到磁盘