下载组件
npm install recorder-core
封装方法
record.ts
//必须引入的核心import Recorder from 'recorder-core';//引入mp3格式支持文件;如果需要多个格式支持,把这些格式的编码引擎js文件放到后面统统引入进来即可import 'recorder-core/src/engine/mp3';import 'recorder-core/src/engine/mp3-engine';//录制wav格式的用这一句就行import 'recorder-core/src/engine/wav';import {RecordType } from './type';const record: RecordType = {RecordApp: null,recBlob: null,/**麦克风授权 */getPermission: (fn: Function | null) => {const newRec = Recorder({type: 'wav',bitRate: 16,sampleRate: 16000, //阿里采样率16000onProcess: function (buffers, powerLevel, duration, bufferSampleRate) {console.log(buffers);},});//打开录音,获得权限newRec.open(() => {record.RecordApp = newRec;fn({status: 'success', data: '开启成功' });},(msg, isUserNotAllow) => {//用户拒绝了录音权限,或者浏览器不支持录音fn({status: 'fail', data: msg });console.log((isUserNotAllow ? 'UserNotAllow,' : '') + '无法录音:' + msg);});},/**开始录音 */startRecorder: () => {if (record.RecordApp && Recorder.IsOpen()) {record.RecordApp.start();}},/** 停止录音 */stopRecorder: (fn: Function | null) => {try {if (!record) {console.error('未打开录音');return;}record.RecordApp.stop((blob, duration) => {console.log('录音成功', blob, '时长:' + duration + 'ms');if (blob) {record.recBlob = blob;const formData = new FormData();formData.append('audio', blob);fn({loading: true });}/* eslint-enable */record.RecordApp.close();record.RecordApp = null;});} catch (err) {fn({err: err });console.error('结束录音出错:' + err);record.RecordApp.close();record.RecordApp = null;}},/**关闭录音,释放麦克风资源 */destroyRecorder: () => {if (record.RecordApp) {record.RecordApp.close();record.RecordApp = null;}},/**暂停 */pauseRecorder: () => {if (record.RecordApp) {record.RecordApp.pause();}},/**恢复继续录音 */resumeRecorder: () => {if (record.RecordApp) {record.RecordApp.resume();}},};export default record;
调用
import record from '/@/utils/record/record';/**初始化 */function init() {record.getPermission(function (permiss) {if (permiss.status == 'fail') {createMessage.warning(permiss.data);} else {record.startRecorder();state.confLoading = true;}});}/**结束录音 */function stopRec() {state.loading = true;state.confLoading = true;record.stopRecorder(function (res) {/**处理 */})}