下载组件

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, //阿里采样率16000
      onProcess: 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) {
        /**处理 */
         })
       
      }

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐