在前端 Vue 项目中使用 js-audio-recorder 组件,可按以下流程进行操作:
- 安装组件:在项目根目录下执行
npm i js-audio-recorder命令,安装该组件。 - 引入组件:在需要使用录音功能的 Vue 组件中,通过
import Recorder from 'js - audio - recorder'引入 Recorder。 - 初始化与使用:在组件的
created钩子函数或setup函数中初始化 Recorder 实例,并定义相关方法来控制录音操作。
具体使用方法如下:
- 创建实例:可在
created中创建 Recorder 实例,如this.recorder = new Recorder()。也可传入参数自定义采样位数、采样率等,如this.recorder = new Recorder({sampleBits: 16, sampleRate: 16000, numChannels: 1})。 - 开始录音:先通过
Recorder.getPermission()获取麦克风权限,成功后调用start方法,如Recorder.getPermission().then(() => {this.recorder.start()})。 - 控制录音:暂停录音调用
pause方法,即this.recorder.pause();继续录音调用resume方法,即this.recorder.resume();停止录音调用stop方法,即this.recorder.stop()。 - 播放录音:调用
play方法播放录制的音频,如this.recorder.play()。 - 销毁实例:录音结束后,可调用
destroy方法销毁实例,释放资源,如this.recorder.destroy()。 - 获取音频数据:可通过
getWAVBlob方法获取录制音频的 WAV 格式 Blob 数据,如const blob = this.recorder.getWAVBlob(),用于上传或其他操作。\
示例:
<template> <div> <h1>音频录制示例</h1> <button @click="startRecording" :disabled="isRecording">开始录音</button> <button @click="pauseRecording" :disabled="!isRecording || isPaused">暂停录音</button> <button @click="resumeRecording" :disabled="!isRecording ||!isPaused">继续录音</button> <button @click="stopRecording" :disabled="!isRecording">停止录音</button> <button @click="playRecording" :disabled="!recordingBlob">播放录音</button> <button @click="downloadRecording" :disabled="!recordingBlob">下载录音</button> </div> </template> <script setup> import Recorder from 'js - audio - recorder'; import { ref } from 'vue'; // 录音状态 const isRecording = ref(false); // 暂停状态 const isPaused = ref(false); // 存储录制的音频Blob const recordingBlob = ref(null); let recorder; const startRecording = async () => { try { await Recorder.getPermission(); recorder = new Recorder(); recorder.start(); isRecording.value = true; isPaused.value = false; } catch (error) { console.error('获取权限或开始录音失败', error); } }; const pauseRecording = () => { if (recorder) { recorder.pause(); isPaused.value = true; } }; const resumeRecording = () => { if (recorder) { recorder.resume(); isPaused.value = false; } }; const stopRecording = () => { if (recorder) { recorder.stop(); isRecording.value = false; isPaused.value = false; recordingBlob.value = recorder.getWAVBlob(); recorder.destroy(); } }; const playRecording = () => { if (recordingBlob.value) { const audioUrl = URL.createObjectURL(recordingBlob.value); const audio = new Audio(audioUrl); audio.play(); } }; const downloadRecording = () => { if (recordingBlob.value) { const link = document.createElement('a'); link.href = URL.createObjectURL(recordingBlob.value); link.download ='recording.wav'; link.click(); } }; </script> <style scoped> button { margin: 10px; } </style>