实现效果:
实现步骤:
1.安装recorder-core
npm i recorder-core
2.引入
我这里使用的是局部引入
import Recorder from 'recorder-core';
同时还需要引入
import 'recorder-core/src/engine/mp3';
import 'recorder-core/src/engine/mp3-engine';
import 'recorder-core/src/engine/wav';
import 'recorder-core/src/extensions/waveview';
3.布局
我这里布局比较简洁
<div>
<el-button @click="recOpen">打开录音权限</el-button>
| <el-button @click="recStart">开始录音</el-button>
<br>
<el-button @click="recStop">结束录音</el-button>
| <el-button @click="recPlay">本地试听</el-button>
</div>
<div style="padding-top: 5px">
<!-- 波形绘制区域 -->
<div style="border: 1px solid #ccc; display: inline-block; vertical-align: bottom">
<div style="height: 100px; width: 300px" ref="recwave"></div>
</div>
</div>
4.具体操作
1.打开权限
async function recOpen() {
try {
await navigator.mediaDevices.getUserMedia({ audio: true });
console.log('录音权限已打开');
rec = Recorder({
type: 'wav',
sampleRate: 16000,
bitRate: 16,
onProcess: (buffers, powerLevel, bufferDuration, bufferSampleRate) => {
if (wave) {
wave.input(buffers[buffers.length - 1], powerLevel, bufferSampleRate);
}
},
});
if (recwave.value) {
wave = Recorder.WaveView({ elem: recwave.value });
}
rec.open(
() => {
console.log('录音已打开');
},
(msg: any, isUserNotAllow: any) => {
console.log((isUserNotAllow ? 'UserNotAllow,' : '') + '无法录音:' + msg);
}
);
} catch (err) {
console.error('无法打开录音权限:', err);
}
}
2.开始录音
function recStart() {
if (!rec) {
console.error('未打开录音');
return;
}
rec.start();
if (recognition) {
recognition.start();
console.log('开始语音识别');
}
console.log('已开始录音');
}
3.结束录音
function recStop() {
if (!rec) {
console.error('未打开录音');
return;
}
if (recognition) {
recognition.stop();
console.log('停止语音识别');
console.log(transcript.value);
}
rec.stop(
(blob: any, duration: any) => {
recBlob = blob;
const localUrl = (window.URL || window.webkitURL).createObjectURL(blob);
console.log('录音成功', blob, localUrl, '时长:' + duration + 'ms');
upload(blob);
rec.close();
rec = null;
},
(err: any) => {
console.error('结束录音出错:' + err);
rec.close();
rec = null;
}
);
}
4.上传至后端
const upload = async (blob: any) => {
const formData = new FormData();
formData.append('file', blob, 'recording.wav');
try {
const response = await axios.post('http://localhost:3000/uploadtape', formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
});
console.log('Upload success:', response.data);
} catch (error) {
console.error('Upload error:', error);
}
}
5.播放录音
function recPlay() {
if (!recBlob) {
console.error('没有录音文件可以播放');
return;
}
const localUrl = URL.createObjectURL(recBlob);
const audio = document.createElement('audio');
audio.controls = true;
document.body.appendChild(audio);
audio.src = localUrl;
audio.play();
setTimeout(() => {
URL.revokeObjectURL(audio.src);
}, 5000);
}