peerConnection.ontrack = function()

in static/js/chat.js [94:131]


    peerConnection.ontrack = function(event) {
         if (event.track.kind === 'audio') {
            let audioElement = document.createElement('audio');
            audioElement.id = 'audioPlayer';
            audioElement.srcObject = event.streams[0];
            audioElement.autoplay = true;

            // Attach debugging event listeners
            audioElement.onplay = () => console.log("Audio element started playing");
            audioElement.onpause = () => console.log("Audio element paused");
            audioElement.onended = () => console.log("Audio playback ended");
            audioElement.onerror = (e) => console.error("Audio element error:", e);             

            console.log("WebRTC audio connected.");
            const container = document.getElementById('remoteVideo');
            container.querySelectorAll('audio').forEach(el => el.remove());
            container.appendChild(audioElement);
         }

         if (event.track.kind === 'video') {
            let videoElement = document.createElement('video');
            videoElement.id = 'videoPlayer';
            videoElement.srcObject = event.streams[0];
            videoElement.autoplay = true;
            videoElement.playsInline = true;
            videoElement.muted = true; // Mute video to allow autoplay without user gesture
            videoElement.onplaying = () => {
               const container = document.getElementById('remoteVideo');
               container.querySelectorAll('video').forEach(el => el.remove());
               container.appendChild(videoElement);
               console.log("WebRTC video connected.");
               // Enable microphone (startRecording button)
               document.getElementById('startRecording').disabled = false;
               sessionActive = true;
            };
            videoElement.play().catch(e => console.error("Error playing video: ", e));
        }        
    };