实现思路
1. 先通过getDisplayMedia获取用户选择显示器或显示器的一部分;
2. 通过MediaRecorder媒体录制;
3. 也可以通过recordrtc插件进行录制, 微信小程序可使用; (npm install recordrtc --save)
<!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>录屏</title>
</head>
<body>
<div id="app">
<!-- 操作流程 先start -> stop -> play -->
<div>
<button @click="doStart">start</button>
<button @click="doPause">pause</button>
<button @click="doResume">resume</button>
<button @click="doStop">stop</button>
<button @click="doPlay">play</button>
</div>
<div style="display: flex;">
<div style="margin-right: 50px;">
<h5>录制屏幕</h5>
<video ref="videoPrivew" autoplay controls width="500" height="300"></video>
</div>
<div>
<h5>播放录制屏幕的信息</h5>
<video ref="video" controls width="500" height="300"></video>
</div>
</div>
</div>
<script src="../lib/vue.js"></script>
<script src="../js/screen.js"></script>
</body>
</html>
1. 通过getDisplayMedia获取流以及MediaRecorder进行录制
async init () {
this.stream = await navigator.mediaDevices.getDisplayMedia();
this.$refs.videoPrivew.srcObject = this.stream
this.recoder = new MediaRecorder(this.stream, { mimeType: 'video/webm;codecs=h264' });
//! 调用它用来处理 dataavailable 事件,该事件可用于获取录制的媒体资源 (在事件的 data 属性中会提供一个可用的 Blob 对象.)
this.recoder.ondataavailable = this.ondataavailable.bind(this)
}
ondataavailable (e) {
this.chunk = e.data
},
doStart () {
this.recoder.start()
console.log(this.recoder);
},
doPause () {
this.recoder.pause()
},
doResume () {
this.recoder.resume()
},
doStop () {
if(this.recoder.state!="inactive"){
this.recoder.stop();
}
},
doPlay () {
console.log('url:', URL.createObjectURL(this.chunk))
this.$refs.video.src = URL.createObjectURL(this.chunk)
}
2. 通过getUserMedia获取流以及RecordRTC插件进行屏幕录制;
// 开始录制
startRecorder () {
this.stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: false })
if (this.recorder) {
this.recorder.destroy()
}
this.recorder = new RecordRTC(this.stream, {
type: 'audio/wav',
recorderType: RecordRTC.StereoAudioRecorder,
numberOfAudioChannels: 1, // 开始单声道
desiredSampRate: 16 * 1000 // 采样率
})
this.recorder.startRecording()
}
// 结束录制
stopRecorder () {
this.recorder.stopRecording(() => {
let blob = this.recorder.getBlob()
})
}