*****视频、音频录制的例子:
//上传文件类型的限定
<input type="file" accept="image/*;capture=camera"> <input type="file" accept="video/mp4;capture=camcorder"> <input type="file" accept="audio/*;capture=microphone">
//调用本地摄像头Demo,其中有一个截屏,上面网址链接才是重点哦
<!doctype html> <html lang="en"> <head> <meta charset=utf-8" /> <title></title> <style> video { border: 1px solid #ccc; display: block; margin: 0 0 20px 0; float:left; } canvas { margin-top: 20px; border: 1px solid #ccc; display: block; } </style> </head> <body> <video width="640" height="480" id="myVideo"></video> <canvas width="640" height="480" id="myCanvas"></canvas> <button id="myButton">截图</button> <button id="myButton2">预览</button> <button id="myButton3"> <a download="video.png">另存为</a> </button> </body> <script> window.addEventListener('DOMContentLoaded',function(){ var cobj=document.getElementById('myCanvas').getContext('2d'); var vobj=document.getElementById('myVideo'); getUserMedia({video:true},function(stream){ vobj.src=stream; vobj.play(); },function(){}); document.getElementById('myButton').addEventListener('click',function(){ cobj.drawImage(vobj,0,0,640,480); document.getElementById('myButton3').children[0].href=cobj.canvas.toDataURL("image/png"); },false); document.getElementById('myButton2').addEventListener('click',function(){ window.open(cobj.canvas.toDataURL("image/png"),'_blank'); },false); },false); function getUserMedia(obj,success,error){ if(navigator.getUserMedia){ getUserMedia=function(obj,success,error){ navigator.getUserMedia(obj,function(stream){ success(stream); },error); } }else if(navigator.webkitGetUserMedia){ getUserMedia=function(obj,success,error){ navigator.webkitGetUserMedia(obj,function(stream){ var _URL=window.URL || window.webkitURL; success(_URL.createObjectURL(stream)); },error); } }else if(navigator.mozGetUserMedia){ getUserMedia=function(obj,success,error){ navigator.mozGetUserMedia(obj,function(stream){ success(window.URL.createObjectURL(stream)); },error); } }else{ return false; } return getUserMedia(obj,success,error); } </script> </html>
作者:林蔚澜 链接:https://www.zhihu.com/question/50750989/answer/155676855 来源:知乎 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
最新chrome禁止了getUserMedia()方法,只接受https认证的网址或者127.0.0.1在你自己电脑上玩
所以只能在火狐上玩:
开摄像头
navigator.getUserMedia({ video: true}, function(stream){ //←这个就是你想要的视频流 startRecording(stream);//录制 }, function(e){ console.log('媒体错误', e); });
然后是录制
很多吃瓜群众信了stackoverflow的邪,用了MediaRecorder.start(时间),这个方法有许多的坑,会不断循环停不下来,停下来了,上传的视频不可以播放
推荐使用如下方法录制并上传
function startRecording() { recorder = new MediaRecorder(localStream); recorder.ondataavailable = function(evt) { videoBlob = new Blob([evt.data], { type: evt.data.type }); } recorder.start(); setTimeout(function(){ console.log("录像结束"); recorder.stop(); //要给一点recorder到videoBlob的时间,必选 setTimeout(function(){ console.log("录像上传"); upload_vedio(); },1000); },10000); }