js webrtc获取桌面并推流的例子
时间: 2024-05-12 09:15:12 浏览: 14
以下是一个基本的 WebRTC 获取桌面并推流的示例:
HTML 代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>WebRTC Screen Sharing Demo</title>
</head>
<body>
<video id="local-video" autoplay muted></video>
<script src="script.js"></script>
</body>
</html>
```
JavaScript 代码:
```js
const startButton = document.createElement('button');
startButton.textContent = 'Start Sharing';
document.body.appendChild(startButton);
const stopButton = document.createElement('button');
stopButton.textContent = 'Stop Sharing';
stopButton.disabled = true;
document.body.appendChild(stopButton);
let desktopStream = null;
let peerConnection = null;
let localVideo = document.getElementById('local-video');
const constraints = {
video: {
cursor: 'always'
},
audio: false
};
startButton.onclick = async () => {
try {
desktopStream = await navigator.mediaDevices.getDisplayMedia(constraints);
localVideo.srcObject = desktopStream;
startButton.disabled = true;
stopButton.disabled = false;
const configuration = {
iceServers: [{ urls: 'stun:stun.l.google.com:19302' }]
};
peerConnection = new RTCPeerConnection(configuration);
desktopStream.getTracks().forEach(track => {
peerConnection.addTrack(track, desktopStream);
});
const offer = await peerConnection.createOffer();
await peerConnection.setLocalDescription(offer);
// Send the offer to the remote peer
// For example, via WebSocket
console.log(offer);
} catch (err) {
console.error(err);
}
};
stopButton.onclick = () => {
desktopStream.getTracks().forEach(track => {
track.stop();
});
localVideo.srcObject = null;
startButton.disabled = false;
stopButton.disabled = true;
};
```
这个示例使用 `getDisplayMedia` 方法获取桌面流,并将其添加到 `RTCPeerConnection` 实例中。然后,它创建一个 SDP offer,设置本地描述符,并将其发送到远程对等端。你需要将 offer 发送到远程对等端,以便该端可以创建一个 answer,并将其发送回来进行连接。