JavascriptでWEBカメラとマイクから音声付ビデオ録画を行う
Javascriptを使うと簡単に音声付ビデオ録画ができます。
以下のソースコードでは録画データ1秒を配列に追加して入れて再生と録画ファイルのダウンロードができます。
実際のサンプル
ソースコード
<button id="start" onclick="startRecording()">録画開始</button><br> <button id="stop" onclick="endRecording()" disabled>録画停止</button><br> <div id="vdiv"></div> <script> var chunks,recorder,velm=null,da=null; function startRecording(){ chunks=[]; //カメラとマイクの使用許可を取得(なるべく320x240のサイズのメディアで届けてほしいと知らせる) navigator.mediaDevices.getUserMedia( { audio:true, video:{ facingMode:"user", width:{ideal:320}, height:{ideal:240} } } ).then( function(stream){ document.querySelector("#stop").removeAttribute("disabled"); document.querySelector("#start").setAttribute("disabled",""); recorder = new MediaRecorder(stream); recorder.ondataavailable = function(el){ //録画データを配列に保存する if (el.data.size>0){ chunks.push(el.data); } } recorder.onstop = onStop; //1000ミリ秒録画されるごとにdataavailableイベントが発生 recorder.start(1000); } ); } function endRecording(){ if(recorder){recorder.stop();} } function onStop(){ if (!chunks.length){return;} document.querySelector("#stop").setAttribute("disabled",""); document.querySelector("#start").removeAttribute("disabled"); var obj=new Blob(chunks,{type:recorder.mimeType}); if(velm==null){ velm=document.createElement("video"); velm.setAttribute("playsInline",true); velm.setAttribute("controls",true); document.getElementById("vdiv").appendChild(velm); document.getElementById("vdiv").appendChild(document.createElement("br")); da=document.createElement("a"); document.getElementById("vdiv").appendChild(da); } da.href=URL.createObjectURL(obj); if(recorder.mimeType.match(/x-matroska/)){ da.download="test.mkv"; }else if(recorder.mimeType.match(/mp4/)){ da.download="test.mp4"; }else if(recorder.mimeType.match(/mpg/)){ da.download="test.mpg"; }else{ da.download="test.webm"; } da.innerHTML="ダウンロード("+da.download+")"; velm.src=URL.createObjectURL(obj); } </script>