我写了一个简单的屏幕录制程序,使用的是 chrome 浏览器,使用了 HTML5 中的 getUserMedia 和 getDisplayMedia 分别录制音频和视频。然后使用 getVideoTracks API 合并音轨,然后使用 MediaRecorder 获得数据流。具体代码如下:
start capture
stop capture
然后是 JS 代码:
const video = document.querySelector("video");
const start = document.querySelector(".start");
const stop = document.querySelector(".stop");
const showVideo = document.querySelector(".showVideo");
async function init(){
showVideo.style.display = "none";
stop.removeAttribute("disabled");
let audioStream = await navigator.mediaDevices.getUserMedia({video: false,audio: true});
// 录屏API:getDisplayMedia
let stream = await navigator.mediaDevices.getDisplayMedia({video: true,audio: true});
video.srcObject = stream;
// 合并音轨(将视频中的片段合并到音频中)
stream.getVideoTracks().forEach(value => audioStream.addTrack(value));
// 此时的 audioStream 就有视频片段了
var mediaRecorder = new MediaRecorder(audioStream,{type: "video/webm"}),
chunks = [];
video.setAttribute("muted",true);
video.setAttribute("autoplay",true);
mediaRecorder.start();
mediaRecorder.ondataavailable = function(e){
chunks.push(e.data);
};
mediaRecorder.onstop = function(){
handleStop(chunks);
};
stop.onclick = function(){
mediaRecorder.stop();
};
}
start.onclick = init;
function handleStop (chunks){
var tracks = video.srcObject.getVideoTracks();
tracks.forEach(track => track.stop());
video.srcObject = null;
showVideo.style.display = "inline-block";
stop.setAttribute("disabled",true);
var blob = new Blob(chunks,{'type': 'video/mp4'});
var videoURL = window.URL.createObjectURL(blob);
chunks = [];
showVideo.src = videoURL;
}
当我把录好的视频播放完,点击保存后,保存的视频没有画面,只有音频。这是为什么?有没有好的方式去保存生成的视频?