From 1a1f389ab749556cef7e3e8752625d3d9724b23f Mon Sep 17 00:00:00 2001 From: 3nd3r Date: Fri, 2 Jan 2026 21:36:26 -0600 Subject: [PATCH] Fix audio autoplay blocking by creating AudioContext only on user interaction --- script.js | 41 ++++++++++++++++++++--------------------- 1 file changed, 20 insertions(+), 21 deletions(-) diff --git a/script.js b/script.js index 0648f57..871caf6 100644 --- a/script.js +++ b/script.js @@ -2090,16 +2090,7 @@ function initListenerMode() { document.body.classList.add('listening-active'); // For global CSS targeting updateGlowIntensity(settings.glowIntensity || 30); - // Setup Audio Context for volume/routing (only if not already created) - if (!listenerAudioContext) { - listenerAudioContext = new (window.AudioContext || window.webkitAudioContext)(); - listenerGainNode = listenerAudioContext.createGain(); - listenerGainNode.gain.value = 0.8; - listenerGainNode.connect(listenerAudioContext.destination); - console.log('🎵 Created new AudioContext for listener mode'); - } else { - console.log('♻️ Reusing existing AudioContext'); - } + // AudioContext will be created when user enables audio to avoid suspension // Create or reuse audio element to handle the MediaSource let audio; @@ -2122,16 +2113,7 @@ function initListenerMode() { document.body.appendChild(audio); console.log('🆕 Created new audio element'); - // Bridge Audio Element to AudioContext (only for new elements) - // Note: createMediaElementSource can only be called once per audio element - try { - const sourceNode = listenerAudioContext.createMediaElementSource(audio); - sourceNode.connect(listenerGainNode); - console.log('🔗 Connected audio element to AudioContext'); - } catch (e) { - console.error('❌ Failed to create MediaElementSource:', e.message); - // This is a critical error, but continue anyway - } + // AudioContext will be created later on user interaction } // Initialize MediaSource for streaming binary chunks @@ -2311,7 +2293,24 @@ async function enableListenerAudio() { console.log('✅ Audio context resumed'); } - // 3. Prepare and start audio playback + // 3. Bridge Audio Element to AudioContext if not already connected + if (window.listenerAudio && !window.listenerAudio._connectedToContext) { + try { + const sourceNode = listenerAudioContext.createMediaElementSource(window.listenerAudio); + if (!listenerGainNode) { + listenerGainNode = listenerAudioContext.createGain(); + listenerGainNode.gain.value = 0.8; + listenerGainNode.connect(listenerAudioContext.destination); + } + sourceNode.connect(listenerGainNode); + window.listenerAudio._connectedToContext = true; + console.log('🔗 Connected audio element to AudioContext'); + } catch (e) { + console.warn('⚠️ Could not connect to AudioContext:', e.message); + } + } + + // 4. Prepare and start audio playback if (window.listenerAudio) { console.log('📊 Audio element state:', { readyState: window.listenerAudio.readyState,