トップへ(mam-mam.net/)

Javascriptでマイクから録音、音声ファイルをダウンロード、サーバーにPOST、再生する

検索:

マイクから録音、再生する

「マイクの使用を開始」ボタンを押すと、マイクをアクティブにします。
次に「録音の開始」ボタンを押すと録音を開始します。




(参考)MediaRecorderを使うとデータを圧縮できますが、コーデック形式はブラウザ毎に異なります

ソースコード

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=0.1, maximum-scale=4,user-scalable=yes">

<script>
  var TMamMicRec=function(control,micOnBtn,recStartBtn,recStopBtn,recMime){
    this.control=control;
    this.micOnBtn   =micOnBtn;
    this.recStartBtn=recStartBtn;
    this.recStopBtn =recStopBtn;
    this.recMime = recMime;
    
    this.stream=null;
    this.mediaRecorder=null;
    this.chunks=[];
    this.recStartBtn.setAttribute("disabled",true);
    this.recStopBtn.setAttribute("disabled",true);
    this.type=null;
    
    this.micOnBtn.addEventListener("click",function(){
      if(navigator.mediaDevices==undefined){
        alert('未対応ブラウザ 又は HTTPS接続していません');
        return;
      }
      navigator.mediaDevices.getUserMedia({audio:true})
      .then(function(stream){
        this.stream=stream;
        
        this.mediaRecorder=new MediaRecorder(this.stream);
        this.mediaRecorder.addEventListener("dataavailable",function(event){
          this.chunks.push(event.data);
          console.log(event.data);
        }.bind(this));
        this.mediaRecorder.addEventListener("stop",function(e){
          // audio/webm;codecs=opus audio/ogg; codecs=opus
          this.type=this.chunks[0].type;
          this.recMime.innerHTML=this.type;
          let blob=new Blob(this.chunks,{"type":this.type});
          this.chunks=[];

          /*
          //ファイルのダウンロードを行う場合
          let aTag=document.createElement("a");
          aTag.href=URL.createObjectURL(blob);
          aTag.download="a.mp4";
          aTag.click();
          */

          /*
          //DataURI変換して<input type="hidden">のvalueに入れてPOSTでサーバーに送る場合
          let fileReaderPost=new FileReader();
          fileReaderPost.addEventListener("load",function(event){
            let formTag=document.createElement('form');
            formTag.method="get";
            formTag.action="post.php";//POST先URL
            let inputTag=document.createElement('input');
            inputTag.type="hidden";
            inputTag.name="record";//POST時の名前
            inputTag.value=event.target.result;//POST時の値
            formTag.appendChild(inputTag);
            this.control.appendChild(formTag);
            formTag.submit();//POST実行する
          }.bind(this));
          fileReaderPost.readAsDataURL(blob);
          */

          //録音したblobをDataURIスキームに変換して<audio>タグでそのまま再生する場合
          let fileReaderAudio=new FileReader();
          fileReaderAudio.addEventListener("load",function(event){
            let audio_play=document.body.querySelector("#audio_play");
            if(audio_play==null){
              audio_play=document.createElement("audio");
              audio_play.setAttribute("controls","true");
              audio_play.setAttribute("id","audio_play");
              audio_play.setAttribute("playsinline","");
              this.control.appendChild(audio_play);
              //document.getElementById("Control").appendChild(audio_play);
            }else{
              audio_play.pause();
              audio_play.currentTime=0;
            }
            audio_play.setAttribute("src",event.target.result);
            //audio_play.src=this.result;
            audio_play.load();
            audio_play.play();
          }.bind(this));
          fileReaderAudio.readAsDataURL(blob);

          this.recStartBtn.removeAttribute("disabled");
          this.recStopBtn.setAttribute("disabled",true);
        }.bind(this));
        this.recStartBtn.removeAttribute("disabled");
        this.micOnBtn.setAttribute("disabled",true);
      }.bind(this)).catch(function(e){
        console.log(e);
        document.getElementById("alert").innerHTML=e;
      }.bind(this));
    }.bind(this));
    this.recStartBtn.addEventListener("click",function(){
      this.recStartBtn.setAttribute("disabled", true);
      this.recStopBtn.removeAttribute("disabled");
      this.mediaRecorder.start();
    }.bind(this));
    this.recStopBtn.addEventListener("click",function(){
      this.mediaRecorder.stop();
    }.bind(this));
  }
  window.addEventListener("DOMContentLoaded",function(){
    mamMicRec=new TMamMicRec(
      document.getElementById("Control"),
      document.getElementById("MicOn"),
      document.getElementById("RecStart"),
      document.getElementById("RecStop"),
      document.getElementById("RecMime")
    );
  });
</script>
</head>
<body>
  <div id="Control">
    <button id="MicOn">マイクの使用を開始</button><br/>
    <button id="RecStart">録音開始</button>
    <button id="RecStop" disabled>録音終了</button><br>
    <div id="RecMime"></div>
  </div>
</body>
</html>