<template>
	<div>
		<el-button type="primary" @click="startRecording" v-if="!videoStart">开始录制</el-button>
		<el-button type="primary" @click="stopRecording" v-else>停止录制</el-button>

	</div>
</template>

<script>
import RecordRTC from 'recordrtc';
export default {
	data() {
		return {
			videoStart: false,
			recorder: null,
			fileName: "",
		}
	},
	props: {
		// fileName:{
		// 	type:String,
		// 	default:new Date().getTime()
		// }
	},
	onLoad() {

	},
	mounted() {

	},
	methods: {
		getAudioVideo(constraintsData) {
			if (navigator.mediaDevices === undefined) {
				navigator.mediaDevices = {};
			}
			if (navigator.mediaDevices.getUserMedia === undefined) {
				navigator.mediaDevices.getUserMedia = function (constraints) {
					// 首先，如果有getUserMedia的话，就获得它
					var getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
					// 一些浏览器根本没实现它 - 那么就返回一个error到promise的reject来保持一个统一的接口
					if (!getUserMedia) {
						return Promise.reject({ code: 404 });
					}

					// 否则，为老的navigator.getUserMedia方法包裹一个Promise

					return new Promise(function (resolve, reject) {
						getUserMedia.call(navigator, constraints, resolve, reject);
					});
				}
			}
			return navigator.mediaDevices.getUserMedia(constraintsData)
		},
		/**
		 * 开始录制
		 */
		startRecording(callback) {
			let _function = (screenStream) => {
				this.addStreamStopListener(screenStream, () => {
					console.log("流停止监听");
					this.stopRecording();
					this.$emit("streamStop", {})
				});
				var options = {
					type: 'video',
					mimeType: 'video/webm',
					disableLogs: false,
					getNativeBlob: false, // enable it for longer recordings
					ignoreMutedMedia: false
				};
				// this.video.srcObject = screenStream;
				this.recorder = RecordRTC(screenStream, options);
				this.recorder.startRecording();
				this.recorder.screen = screenStream;
				this.videoStart = true;
				// callback(true);
			}

			this.getAudioVideo({ audio: true }).then(res => {
				this.captureScreen(_function, true);
				console.log('已点击允许,开启成功');
			}).catch(err => {
				// if (err.code && err.code == 404) {
				// 	console.log('浏览器不支持，请更换浏览器')
				// } else {
					this.captureScreen(_function, false);
					console.log('请检查是否存在麦克风')
				// }
			})
		},
		/**
		 * 停止录制
		 */
		stopRecording(callback) {
			this.recorder.stopRecording(() => {
				// this.video.src = this.video.srcObject = null;
				// this.video.src = URL.createObjectURL(this.recorder.getBlob());
				const url = URL.createObjectURL(this.recorder.getBlob());
				const a = document.createElement("a");
				let videoFile = new File([this.recorder.getBlob()], this.fileName + ".mp4", {
					type: 'video/mp4'
				})
				let downloadUrl = URL.createObjectURL(videoFile);
				document.body.appendChild(a);
				a.style.display = "none";
				a.href = url;
				a.download = this.fileName + ".mp4";
				a.click();
				this.recorder.screen.stop();
				this.recorder.destroy();
				this.recorder = null;
				this.videoStart = false;
				// callback(false);
			});
		},
		//初始化
		captureScreen(callback, type) {
			if (navigator.getDisplayMedia) {
				//录制结束,文件下载
				navigator.getDisplayMedia({
					video: true
				}).then(screenStream => {
					if (type) {
						navigator.mediaDevices.getUserMedia({ audio: true }).then((mic) => {
							screenStream.addTrack(mic.getTracks()[0]);
							callback(screenStream);
						});
					} else {
						callback(screenStream);
					}
				}).catch(function (error) {
					console.log('error', error);
				});
			} else if (navigator.mediaDevices.getDisplayMedia) {
				navigator.mediaDevices.getDisplayMedia({
					video: true
				}).then(screenStream => {
					if (type) {
						navigator.mediaDevices.getUserMedia({ audio: true }).then((mic) => {
							screenStream.addTrack(mic.getTracks()[0]);
							callback(screenStream);
						});
					} else {
						callback(screenStream);
					}
				}).catch(function (error) {
					console.log('error', error);
				});
			} else {
				var error = 'getDisplayMedia API are not supported in this browser.';
				console.log('error', error);
				alert(error);
			}
		},

		//流监听
		addStreamStopListener(stream, callback) {
			stream.addEventListener('ended', function () {
				callback();
				callback = function () { };
			}, false);
			stream.addEventListener('inactive', function () {
				callback();
				callback = function () { };
			}, false);
			stream.getTracks().forEach(function (track) {
				track.addEventListener('ended', function () {
					callback();
					callback = function () { };
				}, false);
				track.addEventListener('inactive', function () {
					callback();
					callback = function () { };
				}, false);
			});
		},

	}
}
</script>

<style>

</style>

