1.获取H5的媒体对象
 function hasUserMedia() {
      navigator.getUserMedia =
        navigator.getUserMedia ||
        navigator.msGetUserMedia ||
        navigator.webkitGetUserMedia ||
        navigator.mozGetUserMedia;
      return !!navigator.getUserMedia;
    }
 
 
    navigator.getUserMedia(
      { video: false, audio: true },   //打开摄像头和麦克风。此处仅使用麦克风
      (stream) => {
        console.log(stream);
        //console.log(window.URL.createObjectURL(stream));        //该方法一直在谷歌浏览器一直报错,所以此处不使用

        record.onclick = function() {                          此处是点击按钮切换音频通话功能
          if(!audioPlay){
            mediaRecorder.start(1000);
            console.log("录音:"+mediaRecorder.state);           
            audioPlay=true;
            audio.srcObject = stream;
            $(".playBtn").css("background-image","url(/assets/img/stop.png)")
          }else{
            mediaRecorder.stop();
            console.log("录音:"+mediaRecorder.state);          
            audioPlay=false;
            audio.srcObject = null;
            $(".playBtn").css(\'background-image\',"url(/assets/img/play.png)")
          }       
      };
        var mediaRecorder=new MediaRecorder(stream);     //创建MediaRecorder对象,用来将获取到的MediaStream媒体对象转换为blob对象
        mediaRecorder.ondataavailable=function(blob){     //此处将blob对象进行base64转换并传输给后台
         //console.log(blob.data)
         const reader = new FileReader();
         reader.onload = function(e) {
           //console.log(e.target === this) // true
           // console.log(this === reader) // true
          // console.log(this.result); // function ProgressEvent() { [native code] }
           mqtt_send("/GussianApi/Media/" + sn, "0|"+this.result);
         };
         reader.readAsDataURL(blob.data);
        }
       
      },
      (error) => {
        console.log(error);
      }
    );

  2.也可以使用navigator.mediaDevices.getUserMedia,两者使用方法类似

navigator.mediaDevices
    .getUserMedia({video:false,audio:true})
    .then(function(stream) {
      console.log(stream)     
    })
    .catch(function(err) {
      console.log("The following error occured: " + err);
    });

  

版权声明:本文为BlingSun原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/BlingSun/p/12794850.html