<div style="width: 540px; height: 300px; border: 1px solid; margin: 0 auto;">
<video width="100%" height="100%" poster="img/01.jpg" controls id="video1">
<source src="" type="video/webm" />
</video>
</div>
<div style="width: 500px; border: 1px solid; margin: 0 auto;">
<button id="lz">录制</button>
<button id="wc">完成</button>
<button id="xz">下载</button>
</div>
<div style="width: 540px; height: 300px; border: 1px solid; margin: 0 auto;">
<video width="100%" height="100%" controls id="video2">
<source src="" type="video/webm" />
</video>
</div>
<script>
let mediaRecorder;
let video = document.querySelector('#video1');
let vplay = document.querySelector('#video2');
let fullBlob;
var types = [
"video/webm",
"audio/webm",
"video/webm\;codecs=vp8",
"video/webm\;codecs=daala",
"video/webm\;codecs=h264",
"audio/webm\;codecs=opus",
"video/mpeg"
];
navigator.mediaDevices.getUserMedia({
//audio: true,
video: {
facingMode: {
exact: "user"
} //默认使用前置摄像头;{ exact: "environment" }为后置摄像头
},
}).then(mediaStream => {
//src 是播多媒体文件的;src属性通常用于指定视频文件的位置(URL)。
//srcObject 是实时流;
console.log(mediaStream)
video.srcObject = mediaStream;
//当指定的音频/视频的元数据已加载时,会发生 loadedmetadata 事件。
// video.onloadedmetadata = function() {
// this.play();
// this.muted = true; //设置或者返回视频是否关闭声音
// }
// 定义mediaRecorder对象
mediaRecorder = new MediaRecorder(mediaStream, {
audioBitsPerSecond: 128000,
videoBitsPerSecond: 2500000,
mimeType: types[0]
});
// 摄像头开启
video.play();
})
// 开始录制视频
document.querySelector("#lz").onclick = () => {
console.log("开始录制")
mediaRecorder.start()
}
// 停止录制
document.querySelector("#wc").onclick = () => {
console.log("停止")
mediaRecorder.stop();
mediaRecorder.ondataavailable = (e) => {
//console.log(e.data)
fullBlob = new Blob([e.data], { //blob数据及格式设置
type:types[0]
});
console.log(fullBlob)
}
}
// 下载
document.querySelector("#xz").onclick = () => {
let blobUrl=window.URL.createObjectURL(fullBlob)
//video.src=obj.slice(5)
console.log("vplay.src:",blobUrl)
vplay.src=blobUrl
const link = document.createElement('a');
link.style.display = 'none';
link.href = blobUrl;
link.download = 'media.mp4';
document.body.appendChild(link);
link.click();
link.remove();
}
</script>