用到了騰訊的im,錄音功能還是要自己實現的,正當我糾結該使用哪一個庫時,發現文檔裏面示例用的是js-audio-recorder
,我很高興。
錄音只能在https、localhost、file下才能進行,否則就說不支持getUserMedia,我很無語,因爲我電腦不支持錄音,本地啓動也不支持https,最後只能連藍牙耳機。
js-audio-recorder
這個庫迷人格式是wav,後端只支持mp3,說是用lampjs,一頓操作,報錯"ReferenceError: MPEGMode is not defined",查了半天,大多數方案都是編輯文件node_modules/lamejs夾中的相應文件等等,這太不靠譜了。
於是乎我嘗試了https://github.com/xiangyuecn/Recorder,導入語句
import Recorder from 'recorder-core'
import 'recorder-core/src/engine/mp3'
import 'recorder-core/src/engine/mp3-engine'
當切換爲語音交互時,進行初始化,切換爲文本交互時釋放資源,open
在用戶沒有授權時會彈出系統彈窗,在Chrome瀏覽器中訪問chrome://settings/content/microphone
可以管理網站授權。
this.isSendText = !this.isSendText;
if (!this.isSendText) {
this.recordInstance = Recorder({
type: "mp3",
sampleRate: 16000,
bitRate: 16,
});
this.recordInstance.open();
}
else {
this.recordInstance.close()
}
beforeDestroy
時也釋放下
if (this.recordInstance) {
this.recordInstance.close();
}
錄音結束直接調用stop方法
this.recordInstance.stop((blob, duration) => {
});
獲得mp3文件使用如下代碼
let audioFile = new File([blob], 'voice.mp3', { type: 'audio/mp3' });
audioFile.duration = duration;
2022 - 11 - 07
ios13的瀏覽器本身就是不支持錄音的
iso瀏覽器在通過js播放音頻時,不觸發onloadeddata
,可以用ondurationchange
代替,如果發現錄製的聲音不能播放,可能是這個問題導致的