文章目录
1.增加 html 的一行代码
<script src="/static/js/screen_share.js"></script>
完整代码如下
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>1v1屏幕共享示例</title>
<style type="text/css">
video {
width: 320px;
height: 240px;
border: 1px solid black;
}
button {
background-color: #d84a38;
border: none;
color: white;
margin: 0 1em 0 0;
padding: 0.5em 0.7em 0.6em 0.7em;
}
</style>
</head>
<body>
<h3>1v1屏幕共享示例</h3>
<div>
<video id="localVideo" autoplay controls></video>
<video id="remoteVideo" autoplay controls></video>
</div>
<button id="btnStartPush">开始推流</button>
<button id="btnStopPush">停止推流</button>
<button id="btnStartPull">开始拉流</button>
<button id="btnStopPull">停止拉流</button>
<script src="/static/js/screen_share.js"></script>
</body>
</html>
2. 在 static 目录下创建 js 文件夹,并在 js 文件夹下面创建 screen_share.js 文件
screen_share.js 文件内容如下:
'use strict';
const localVideo = document.getElementById('localVideo');
const startPushBtn = document.getElementById('btnStartPush');
startPushBtn.addEventListener('click', startPush);
function startPush() {
console.log("start push stream");
window.postMessage({type: 'SS_UI_REQUEST', text: "push"}, '*');
}
window.addEventListener('message', function(event) {
console.log("addEventListener");
if (event.origin != window.location.origin) {
return;
}
if (event.data.type && event.data.type === 'SS_DIALOG_SUCCESS') {
console.log("用户同意屏幕共享, streamId: " + event.data.streamId);
startScreenStreamFrom(event.data.streamId);
} else if (event.data.type && event.data.type === 'SS_DIALOG_CANCEL') {
console.log("用户取消屏幕共享");
}
});
function startScreenStreamFrom(streamId) {
const constraints = {
audio: false,
video: {
mandatory: {
chromeMediaSource: 'desktop',
chromeMediaSourceId: streamId,
maxWidth: window.screen.width,
maxHeight: window.screen.height
}
}
};
navigator.mediaDevices.getUserMedia(constraints).
then(handleSuccess).catch(handleError);
}
function handleSuccess(stream) {
console.log("get screen stream success");
localVideo.srcObject = stream;
}
function handleError(err) {
console.log("get screen stream error: " + err.toString());
}
3. 访问 htpps 的网址
https://www.liangzixuexi.com:8081/static/share.html