navigator.mediaDevices.getUserMedia 录制视频及拍照:
1.录制视频功能未上传后端,只转成了FormData格式数据
2.拍照功能正常
3.直接上码:
html:
<div style="width: 100%;height: 100%;margin:0 auto;padding: 0;text-align: center;">
<video id="video" autoplay style="width: 100%;margin:0 auto 20px;"></video>
<div style="width:100%;margin:0 auto 24px;text-align: center;">
<button id="record" style="width:100px;height: 30px;">录制</button>
<button id="capture" style="width:100px;height: 30px;">拍照</button>
</div>
<canvas id="canvas" width="480" height="320" style="margin:0 auto;"></canvas>
</div>
js:
var video = document.getElementById('video');
var canvas = document.getElementById('canvas');
var record = document.getElementById('record');
var capture = document.getElementById('capture');
var context = canvas.getContext('2d');
var constraints = { audio: true, video: true };
var chunks =[];
var recorderFile=null;
var mediaRecorder = null;
navigator.mediaDevices.getUserMedia(constraints).then(function(stream){
//兼容webkit核心浏览器
var CompatibleURL = window.URL || window.webkitURL;
//将视频流转化为video的源
video.srcObject = stream;
video.play();//播放视频
mediaRecorder = new MediaRecorder(stream);
mediaRecorder.ondataavailable = function(e) {
chunks.push(e.data);
}
mediaRecorder.onstop = function(e) {
recorderFile = new Blob(chunks, {
'type': mediaRecorder.mimeType
});
chunks = [];
let dateTime=getCurrentDate();
var file = new File([recorderFile], 'video-' + dateTime + '.mp4', {
type: 'video/mp4'
});
console.log(file);
var formData = new FormData();
formData.append("file", file);
console.log(formData);
};
mediaRecorder.start(1000);
}).catch(function(error){
alert('访问用户媒体失败:',error.name,error.message);
});
record.addEventListener('click',function() {
mediaRecorder.stop();
mediaRecorder.start(1000);
});
capture.addEventListener('click',function() {
context.drawImage(video,0,0,480,320);
});
function getCurrentDate() {
var now = new Date();
var year = now.getFullYear(); //得到年份
var month = now.getMonth();//得到月份
var date = now.getDate();//得到日期
var day = now.getDay();//得到周几
var hour = now.getHours();//得到小时
var minu = now.getMinutes();//得到分钟
var sec = now.getSeconds();//得到秒
month = month + 1;
if (month < 10) month = "0" + month;
if (date < 10) date = "0" + date;
if (hour < 10) hour = "0" + hour;
if (minu < 10) minu = "0" + minu;
if (sec < 10) sec = "0" + sec;
var time = year + "-" + month + "-" + date+ "-" + hour + "-" + minu + "-" + sec;
return time;
}
效果图:

本文介绍如何使用navigator.mediaDevices.getUserMedia API实现网页端的视频录制与拍照功能。通过示例代码展示了如何设置HTML界面,利用JavaScript进行视频流获取、录制、停止以及拍照,并将录制的视频文件转换为FormData格式。

被折叠的 条评论
为什么被折叠?



