Vue中使用js-audio-recorder实现录音
使用步骤:
- 安装
npm i js-audio-recorder
- vue文件中引入
import Recorder from 'js-audio-recorder'
- 使用
- mounted 中创建recorder
mounted() {
this.recorder = new Recorder({
sampleBits: 16, // 采样位数,支持 8 或 16,默认是16
sampleRate: 16000, // 采样率,支持 11025、16000、22050、24000、44100、48000,根据浏览器默认值,我的chrome是48000
numChannels: 1, // 声道,支持 1 或 2, 默认是1
});
},
- methods中使用Recorder中相关方法
methods: {
mousedown() {
// Recorder.getPermission用于获取网页麦克风权限
Recorder.getPermission().then(
() => {
this.recorder.start(); // 开始录音
},
(error) => {
this.$message({
message:
"请先允许该网页使用麦克风",
type: "info",
});
}
);
},
mouseup() {
let that = this;
this.recorder.stop(); // 停止录音
if (this.recorder == null || this.recorder.duration === 0) {
this.$message({
message: "请先录音",
type: "error",
});
return false;
}
const formData = new FormData();
const blob = this.recorder.getWAVBlob(); // 获取wav格式音频数据
// 此处获取到blob对象后需要设置fileName满足当前项目上传需求,其它项目可直接传把blob作为file塞入formData
const newbolb = new Blob([blob], { type: "audio/wav" });
const fileOfBlob = new File([newbolb], new Date().getTime() + ".wav");
formData.append("file", fileOfBlob);
// const url = window.URL.createObjectURL(fileOfBlob);
// this.src = url;
// this.recorder.downloadWAV(); // 下载语音文件
// audioToText上传音频文件接口
that.$api.audioToText(formData).then((res) => {
if (res.code == 200) {
if (res.data.status == 20000000) {
// 接口返回音频转换的文字
this.keyWord = res.data.result;
// 路由跳转并将文字带过去
that.$router.push({
path: "/resourceStatistics",
query: {
keyWord: that.keyWord,
},
});
} else {
this.$message({
message: "系统异常,请稍后再试!",
type: "error",
});
}
}
});
},
},
备注
- 采样率一定要和后端保持一致,否则语音转文字不准确(后端使用阿里云语音)
- 本地localhost可以使用语音,http协议(不论本地或线上)均无法使用语音,这是因为网页认为http协议是不安全的,因此http请求的 chrome,edge, fireFox 等主流浏览器由于安全限制将不会暴露getUserMedia 方法,所以就不能够访问用户的媒体设备。
http协议无法使用麦克风权限的解决方案:
-
chrome浏览器访问如下地址:
chrome://flags/#unsafely-treat-insecure-origin-as-secure
-
chrome浏览器配置
-
edge浏览器配置
edge://flags/#unsafely-treat-insecure-origin-as-secure