使用插件
使用js-audio-recorder
插件進行錄音,使用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, // 采樣位數,支持 8 或 16,默認是16
sampleRate: 16000, // 采樣率,支持 11025、16000、22050、24000、44100、48000,根據瀏覽器默認值,我的chrome是48000
numChannels: 2, // 聲道,支持 1 或 2, 默認是1
});
console.log('recorder.value',recorder.value)
}, (error) => {
console.log(`${error.name} : ${error.message}`);
});
})
3、開始錄音
if(!recorder.value){
recorder.value= new Recorder({
sampleBits: 16, // 采樣位數,支持 8 或 16,默認是16
sampleRate: 16000, // 采樣率,支持 11025、16000、22050、24000、44100、48000,根據瀏覽器默認值,我的chrome是48000
numChannels: 2, // 聲道,支持 1 或 2, 默認是1
});
}
recorder.value.start().then((res) => {
}, (error) => {
// 出錯了
console.log(`${error?.name} : ${error?.message}`);
});
}
4、結束錄音并獲取pcm 數據
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:()=>{ // 監聽播放結束
}
});
player.value.feed(pcmData.value);
5 獲取到的pcmDataView 轉換成base64 使用websocket發送給服務端
const pcmDataView = recorder.value.getPCM();
const base64String = window.btoa(String.fromCharCode(...new Uint8Array(pcmDataView.buffer)))
6 前端獲取服務端返回的base64,轉成
const base64 = atob(base64String); // 將 Base64 字符串解碼為二進制數據
const bytes = new Uint8Array(base64.length);
for (let i = 0; i < base64.length; i++) {
bytes[i] = base64.charCodeAt(i);
}
const arrayBuffer = bytes.buffer; // 將 Uint8Array 轉換為 ArrayBuffer