|
| 1 | +<!DOCTYPE html> |
| 2 | +<html lang="en"> |
| 3 | +<head> |
| 4 | + <meta charset="UTF-8"> |
| 5 | + <meta name="viewport" content="width=device-width, initial-scale=1.0"> |
| 6 | + <title>Simple Video Call with PeerJS</title> |
| 7 | +</head> |
| 8 | +<body> |
| 9 | + <h1>Video Call</h1> |
| 10 | + <video id="localVideo" autoplay playsinline></video> |
| 11 | + <video id="remoteVideo" autoplay playsinline></video> |
| 12 | + |
| 13 | + <input type="text" id="roomId" placeholder="Enter room ID"> |
| 14 | + <button id="joinButton">Join Call</button> |
| 15 | + |
| 16 | + <script src="https://cdn.jsdelivr.net/npm/peerjs@1.3.2/dist/peerjs.min.js"></script> |
| 17 | + <script> |
| 18 | + const localVideo = document.getElementById('localVideo'); |
| 19 | + const remoteVideos = document.getElementById('remoteVideos'); |
| 20 | + const joinButton = document.getElementById('joinButton'); |
| 21 | + const roomIdInput = document.getElementById('roomId'); |
| 22 | + |
| 23 | + let localStream; |
| 24 | + let peer; |
| 25 | + let connections = []; |
| 26 | + |
| 27 | + joinButton.onclick = async () => { |
| 28 | + const roomId = roomIdInput.value; |
| 29 | + if (!roomId) { |
| 30 | + alert('Please enter a room ID.'); |
| 31 | + return; |
| 32 | + } |
| 33 | + |
| 34 | + // Get local stream |
| 35 | + localStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true }); |
| 36 | + localVideo.srcObject = localStream; |
| 37 | + |
| 38 | + // Initialize PeerJS |
| 39 | + peer = new Peer(); |
| 40 | + |
| 41 | + peer.on('open', id => { |
| 42 | + // Connect to the signaling server (use WebSocket, Firebase, etc.) |
| 43 | + // For simplicity, we assume there's a way to get a list of peers in the room |
| 44 | + fetch(`https://your-server.com/peers-in-room?roomId=${roomId}`) |
| 45 | + .then(response => response.json()) |
| 46 | + .then(peers => { |
| 47 | + peers.forEach(peerId => { |
| 48 | + if (peerId !== id) { |
| 49 | + const call = peer.call(peerId, localStream); |
| 50 | + call.on('stream', addRemoteStream); |
| 51 | + connections.push(call); |
| 52 | + } |
| 53 | + }); |
| 54 | + }); |
| 55 | + }); |
| 56 | + |
| 57 | + // Listen for incoming calls |
| 58 | + peer.on('call', call => { |
| 59 | + call.answer(localStream); // Answer the call with our local stream |
| 60 | + call.on('stream', addRemoteStream); |
| 61 | + connections.push(call); |
| 62 | + }); |
| 63 | + }; |
| 64 | + |
| 65 | + function addRemoteStream(stream) { |
| 66 | + const videoElement = document.createElement('video'); |
| 67 | + videoElement.srcObject = stream; |
| 68 | + videoElement.autoplay = true; |
| 69 | + videoElement.playsInline = true; |
| 70 | + remoteVideos.appendChild(videoElement); |
| 71 | + } |
| 72 | + </script> |
| 73 | +</body> |
| 74 | +</html> |
0 commit comments