#localVideoContainer {
width: 320px;
height: 240px;
margin-bottom: 20px;
}
#remoteVideoContainer {
width: 320px;
height: 240px;
}
#controls {
margin-top: 20px;
}
button {
margin-right: 10px;
}
// Get video elements
const localVideo = document.getElementById('localVideo');
const remoteVideo = document.getElementById('remoteVideo');
// Get buttons
const startButton = document.getElementById('startButton');
const endButton = document.getElementById('endButton');
// Variables for stream and peer connection
let localStream;
let remoteStream;
let peerConnection;
// Start button click event handler
startButton.addEventListener('click', async () => {
try {
// Get local media stream
localStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
localVideo.srcObject = localStream;
// Create peer connection
const configuration = { iceServers: [{ urls: 'stun:stun.stunprotocol.org' }] };
peerConnection = new RTCPeerConnection(configuration);
// Add local stream to peer connection
localStream.getTracks().forEach((track) => {
peerConnection.addTrack(track, localStream);
});
// Set remote video element source when remote stream is added
peerConnection.ontrack = (event) => {
remoteVideo.srcObject = event.streams[0];
remoteStream = event.streams[0];
};
// Generate offer and set local description
const offer = await peerConnection.createOffer();
await peerConnection.setLocalDescription(offer);
// Send offer to the other user (signaling server communication is omitted here)
// You would typically send the offer to the other user via a signaling server
// Handle the other user's answer (signaling server communication is omitted here)
// You would typically receive the answer from the other user via a signaling server
const answer = /* Received answer from the other user */;
await peerConnection.setRemoteDescription(answer);
} catch (error) {
console.error('Error starting video chat:', error);
}
});
// End button click event handler
endButton.addEventListener('click', () => {
// Stop both local and remote streams
localStream.getTracks().forEach((track) => track.stop());
remoteStream.getTracks().forEach((track) => track.stop());
// Close the peer connection
peerConnection.close();
// Reset video elements
localVideo.srcObject = null;
remoteVideo.srcObject = null;
});
0 Comments