getDisplayMedia
MediaRecorder
下载的视频格式一般播放器放不了!【vlc播放,或者使用ffmpeg转下码】
index.html文件如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Screen Record</title>
<style>
#video {
border: 1px solid #999;
width: 98%;
max-width: 860px;
}
.error {
color: red;
}
.warn {
color: orange;
}
.info {
color: darkgreen;
}
</style>
</head>
<body>
<p> Start Capture -> Stop Capture -> download</p>
<p>
<button id="start">Start Capture</button>
<button id="stop">Stop Capture</button>
<button onclick="download()">download</button>
</p>
<video id="video" autoplay></video>
<br>
<strong>Log:</strong>
<br>
<pre id="log"></pre>
</body>
<script>
let recordedBlobs
let recorder
const videoElem = document.getElementById("video");
const logElem = document.getElementById("log");
const startElem = document.getElementById("start");
const stopElem = document.getElementById("stop");
// Options for getDisplayMedia()
const displayMediaOptions = {
video: {
cursor: "never"
},
audio: true
};
// Set event listeners for the start and stop buttons
startElem.addEventListener("click", function (evt) {
startCapture();
}, false);
stopElem.addEventListener("click", function (evt) {
stopCapture();
}, false);
async function startCapture() {
logElem.innerHTML = "";
try {
const stream = await navigator.mediaDevices.getDisplayMedia(displayMediaOptions);
videoElem.srcObject = stream;
const chunks = [];
recorder = new MediaRecorder(stream, { mimeType: "video/webm; codecs=vp9" });
recorder.start();
recorder.onstop = event => {
recordedBlobs = new Blob(chunks, {
type: 'video/mp4',
codecs: 'h264'
});
}
recorder.ondataavailable = event => {
chunks.push(event.data);
};
} catch (err) {
console.error("Error: " + err);
}
}
function stopCapture() {
recorder.stop();
console.info(videoElem.srcObject)
let tracks = videoElem.srcObject.getTracks();
console.info(tracks)
tracks.forEach(track => track.stop());
videoElem.srcObject = null;
}
function download() {
stopCapture();
const url = URL.createObjectURL(recordedBlobs);
const a = document.createElement('a');
document.body.appendChild(a);
a.style.display = 'none';
a.href = url;
a.download = 'test.mp4';
a.click();
window.URL.revokeObjectURL(url);
}
</script>
</html>