js屏幕录制

javascript屏幕录制

新版本浏览器支持js的屏幕录制功能,用到了navigator.mediaDevices.getDisplayMedia方法和MediaRecorder类。
demo:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>js屏幕录制</title>
</head>
<body>
<div>
<video class="video" width="600px" controls></video>
</div>
<div>
<button class="record-btn">record</button>
<button class="stop-btn" style="display: none;">stop</button>
</div>
</body>
<script>
let mediaRecorder, stream;
let btnRecord = document.querySelector(".record-btn")
let btnStop = document.querySelector(".stop-btn")

btnRecord.addEventListener("click", async function () {
btnStop.style.display = 'block';
btnRecord.style.display = 'none';

stream = await navigator.mediaDevices.getDisplayMedia({
video: true
})
// 需要更好的浏览器支持
const mime = MediaRecorder.isTypeSupported("video/webm; codecs=vp9")
? "video/webm; codecs=vp9"
: "video/webm"
mediaRecorder = new MediaRecorder(stream, {
mimeType: mime
})

let chunks = []
mediaRecorder.addEventListener('dataavailable', function(e) {
chunks.push(e.data)
})

mediaRecorder.addEventListener('stop', function(){
let blob = new Blob(chunks, {
type: chunks[0].type
})
let url = URL.createObjectURL(blob)

let video = document.querySelector("video")
video.src = url

let a = document.createElement('a')
a.href = url
a.download = 'video.webm'
a.click()
})
// 必须手动启动
mediaRecorder.start()
})

btnStop.addEventListener('click', function(evt) {
btnStop.style.display = 'none';
btnRecord.style.display = 'block';
// 隐藏记录的图标
stream.getTracks() // get all tracks from the MediaStream
.forEach( track => track.stop() ); // stop each of them

mediaRecorder.stop();
}, false);
</script>
</html>