注意这里avigator.mediaDevices.getUserMedia(),发布到线上需要安全的域名即需要https或者本地运行localhost,才能访问avigator.mediaDevices.getUserMedia API,要不然会直接报undefined**
//开始录音
const startRecord = async () => {
try {
setRecordingStartTime(Date.now());
medisStream.current = await navigator.mediaDevices.getUserMedia({
audio: true,
video: false,
});
recorder.current = new MediaRecorder(medisStream.current);
mediaBlobs.current = []; // 清空录音数据数组,实现每次录音都是单独的切片,而不是带有之前音频的缓存
recorder.current.ondataavailable = (blobEvent) => {
mediaBlobs.current.push(blobEvent.data);
};
recorder.current?.start();
} catch (error) {
alert(`无法录音,${error}`);
console.log('error', error);
}
};
//录音完成
const stopRecord = async () => {
recorder.current?.stop();
medisStream.current?.getTracks().forEach((track) => track.stop());
if (recorder.current) {
recorder.current.onstop = () => {
const blob = new Blob(mediaBlobs.current, { type: 'audio/wav' });
//此处便是获取到的录音的音频
const mediaUrl = URL.createObjectURL(blob);
);
};
}
};