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 remoteVideo = document . getElementById ( 'remoteVideo' ) ;
20+ const joinButton = document . getElementById ( 'joinButton' ) ;
21+ const roomIdInput = document . getElementById ( 'roomId' ) ;
22+
23+ let localStream ;
24+ let peer ;
25+
26+ joinButton . onclick = async ( ) => {
27+ const roomId = roomIdInput . value ;
28+ if ( ! roomId ) {
29+ alert ( 'Please enter a room ID.' ) ;
30+ return ;
31+ }
32+
33+ // Get local stream
34+ localStream = await navigator . mediaDevices . getUserMedia ( { video : true , audio : true } ) ;
35+ localVideo . srcObject = localStream ;
36+
37+ // Initialize PeerJS
38+ peer = new Peer ( ) ;
39+
40+ // Listen for call event
41+ peer . on ( 'call' , call => {
42+ call . answer ( localStream ) ; // Answer the call with our local stream
43+ call . on ( 'stream' , stream => {
44+ remoteVideo . srcObject = stream ; // Show stream in remote video element
45+ } ) ;
46+ } ) ;
47+
48+ // Connect to the room
49+ const conn = peer . connect ( roomId ) ;
50+ conn . on ( 'open' , ( ) => {
51+ const call = peer . call ( roomId , localStream ) ;
52+ call . on ( 'stream' , stream => {
53+ remoteVideo . srcObject = stream ; // Show stream in remote video element
54+ } ) ;
55+ } ) ;
56+ } ;
57+ </ script >
58+ </ body >
59+ </ html >
0 commit comments