使用插件
使用js-audio-recorder 插件進(jìn)行錄音,使用pcm-player插件播放pcm 格式的音頻
錄音
1、安裝js-audio-recorder
npm i js-audio-recorder
2、使用
import Recorder from 'js-audio-recorder';
onMounted(()=>{
Recorder.getPermission().then(() => {
recorder.value= new Recorder({
sampleBits: 16, // 采樣位數(shù),支持 8 或 16,默認(rèn)是16
sampleRate: 16000, // 采樣率,支持 11025、16000、22050、24000、44100、48000,根據(jù)瀏覽器默認(rèn)值,我的chrome是48000
numChannels: 2, // 聲道,支持 1 或 2, 默認(rèn)是1
});
console.log('recorder.value',recorder.value)
}, (error) => {
console.log(`${error.name} : ${error.message}`);
});
})
3、開始錄音
if(!recorder.value){
recorder.value= new Recorder({
sampleBits: 16, // 采樣位數(shù),支持 8 或 16,默認(rèn)是16
sampleRate: 16000, // 采樣率,支持 11025、16000、22050、24000、44100、48000,根據(jù)瀏覽器默認(rèn)值,我的chrome是48000
numChannels: 2, // 聲道,支持 1 或 2, 默認(rèn)是1
});
}
recorder.value.start().then((res) => {
}, (error) => {
// 出錯(cuò)了
console.log(`${error?.name} : ${error?.message}`);
});
}
4、結(jié)束錄音并獲取pcm 數(shù)據(jù)
recorder.value.stop()
pcmData.value=recorder.value.getPCM()
播放
1、安裝 pcm-player
npm i pcm-player
2、使用
import PCMPlayer from 'pcm-player'
3、 播放
player.value = new PCMPlayer({
inputCodec: 'Int16',
channels: 2,
sampleRate: 16000,
flushTime: 2000,
onended:()=>{ // 監(jiān)聽播放結(jié)束
}
});
player.value.feed(pcmData.value);
5 獲取到的pcmDataView 轉(zhuǎn)換成base64 使用websocket發(fā)送給服務(wù)端
const pcmDataView = recorder.value.getPCM();
const base64String = window.btoa(String.fromCharCode(...new Uint8Array(pcmDataView.buffer)))
6 前端獲取服務(wù)端返回的base64,轉(zhuǎn)成
const base64 = atob(base64String); // 將 Base64 字符串解碼為二進(jìn)制數(shù)據(jù)
const bytes = new Uint8Array(base64.length);
for (let i = 0; i < base64.length; i++) {
bytes[i] = base64.charCodeAt(i);
}
const arrayBuffer = bytes.buffer; // 將 Uint8Array 轉(zhuǎn)換為 ArrayBuffer