vue 录音流程 RecordRTC
npm install recordrtc
import RecordRTC from "recordrtc";
<!-- 音频播放器,用于播放录音 -->
<audio v-show="false" ref="audioPlayer" controls></audio>
async startRecording() {
if (!navigator.mediaDevices) {
console.error("浏览器不支持mediaDevices.");
ElMessage.error("浏览器不支持mediaDevices.");
return;
}
this.audioUrl = null;
try {
const stream = await navigator.mediaDevices.getUserMedia({
audio: true,
});
const options = {
type: "audio",
mimeType: "audio/wav",
recorderType: RecordRTC.StereoAudioRecorder,
numberOfAudioChannels: 1,
desiredSampRate: 24000,
checkForInactiveTracks: true,
};
this.recorder = new RecordRTC(stream, options);
this.recorder.startRecording();
this.isRecording = true;
} catch (err) {
console.error("无法获取麦克风权限:", err);
ElMessage.error("无法获取麦克风权限.");
}
},
async stopRecording() {
if (this.recorder) {
await new Promise((resolve) => {
this.recorder.stopRecording(() => {
this.blobData = this.recorder.getBlob();
this.audioUrl = URL.createObjectURL(this.blobData);
this.isRecording = false;
this.$refs.audioPlayer.src = this.audioUrl;
let stream = this.recorder.stream;
if (stream) {
stream.getTracks().forEach((track) => track.stop());
}
this.recorder.destroy();
this.recorder = null;
resolve();
});
});
}
this.isRecording = false;
},
playRecording() {
const audioPlayer = this.$refs.audioPlayer;
if (audioPlayer) {
audioPlayer.play();
}
},