A-A+

h5 js录音demo

2020年09月10日 JavaScript 暂无评论 阅读 9 次

h5 js录音demo

/* eslint-disable */
//构造函数
const Recorder = function(config){
    let _this = this
    config = config || {} // 初始化配置对象
    config.sampleRate = config.sampleRate || 44100 // 采样频率,默认为44100Hz(标准MP3采样率)
    config.bitRate = config.bitRate || 128 // 比特率,默认为128kbps(标准MP3质量)
    navigator.getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.getUserMedia || (navigator.mediaDevices && navigator.mediaDevices.getUserMedia)
    window.AudioContext = window.AudioContext || window.webkitAudioContext
    if(navigator.getUserMedia){
        navigator.getUserMedia({ audio: true },
        function (stream) {
          let context = new AudioContext()
          let microphone = context.createMediaStreamSource(stream) // 媒体流音频源
          let processor = context.createScriptProcessor(16384, 1, 1) // js音频处理器
          let successCallback = null 
          let errorCallback = null
          let worker = null

          config.sampleRate = context.sampleRate
          processor.onaudioprocess = function(event){
            //监听音频录制过程
            let buffer = event.inputBuffer.getChannelData(0)
            worker.postMessage({ cmd: 'encode', buf: buffer })
          }
          worker = new Worker('https://m.allinmd.cn/inside/h5/static/js/worker.js') // 开启后台线程
          worker.onmessage = function(e){ // 主线程监听后台线程,实时通信
            switch(e.data.cmd) {
                case 'init':
                    console.log('初始化成功')
                    config.success && config.success()
                    break;
                case 'end':
                    if(successCallback){
                        let blob = new Blob(e.data.buf, { type: 'audio/mp3' })
                        successCallback(blob)
                        console.log('MP3大小:' + blob.size + '%cB', 'color:#0000EE')
                    }
                    break;
                case 'error':
                    errorCallback && errorCallback(e.data.error)
                    break;
                default:
                    console.log('ERR: ' + e.data);
            }
          }
          // 开始录音
          _this.start = function(){
            if(processor && microphone){
              microphone.connect(processor);
              processor.connect(context.destination)
              console.log('start....');
            }
           }

           // 结束录音
            _this.stop = function(){
              if(processor && microphone){
                microphone.disconnect()
                processor.disconnect()
                console.log('end....')
              }
            }

            // 获取blob格式录音文件
            _this.getBlob = function(onSuccess, onError){
              successCallback = onSuccess
              errorCallback = onError
              worker.postMessage({ cmd: 'finish' })
            }

            worker.postMessage({
              cmd: 'init',
              config: {
                sampleRate: config.sampleRate,
                bitRate: config.bitRate
              }
            })
        },
        function (error) {
            let msg
            switch(error.code || error.name){
              case 'PermissionDeniedError':
              case 'PERMISSION_DENIED':
              case 'NotAllowedError':
                msg = '用户拒绝访问麦克风'
                break;
              case 'NOT_SUPPORTED_ERROR':
              case 'NotSupportedError':
                msg = '浏览器不支持麦克风'
                break;
              case 'MANDATORY_UNSATISFIED_ERROR':
              case 'MandatoryUnsatisfiedError':
                msg = '找不到麦克风设备'
                break;
              default:
                msg = '无法打开麦克风'
                break;
            }
            alert(msg);
            config.error && config.error(msg)
        })
    }else{
      alert('当前浏览器不支持录音功能')
    }
}

export default Recorder
标签:

给我留言

Copyright © web前端技术开发个人博客 保留所有权利  京ICP备14060653号 Theme  Ality

用户登录