Audio: fix inconsistent init — lazy AudioContext, no premature creation

restore() was creating AudioContext without user gesture (on page load
when volume was saved), causing browser to permanently suspend it.
Now restore() only sets flags; AudioContext created lazily on first
sonifyPacket() call or setEnabled() click. Pending volume applied
when context is finally created.
This commit is contained in:
you
2026-03-22 17:25:42 +00:00
parent f206ae48ef
commit 0dbe5fd229
2 changed files with 12 additions and 8 deletions
+11 -7
View File
@@ -12,7 +12,8 @@
let bpm = 120;
let activeVoices = 0;
const MAX_VOICES = 12;
let currentVoice = null; // active voice module
let currentVoice = null;
let _pendingVolume = 0.3; // active voice module
// === Shared Helpers (available to voice modules) ===
@@ -79,14 +80,18 @@
}
audioCtx = new (window.AudioContext || window.webkitAudioContext)();
masterGain = audioCtx.createGain();
masterGain.gain.value = 0.3;
masterGain.gain.value = _pendingVolume;
masterGain.connect(audioCtx.destination);
}
// === Engine: Sonify ===
function sonifyPacket(pkt) {
if (!audioEnabled || !audioCtx || !currentVoice) return;
if (!audioEnabled || !currentVoice) return;
// Lazy-init AudioContext on first actual packet (may not have user gesture,
// but browser will auto-resume when it gets one)
if (!audioCtx) initAudio();
if (!audioCtx) return;
if (audioCtx.state === 'suspended') audioCtx.resume();
if (activeVoices >= MAX_VOICES) return;
@@ -166,10 +171,9 @@
const savedBpm = localStorage.getItem('live-audio-bpm');
if (savedBpm) bpm = parseInt(savedBpm, 10) || 120;
const savedVol = localStorage.getItem('live-audio-volume');
if (savedVol) {
initAudio();
if (masterGain) masterGain.gain.value = parseFloat(savedVol) || 0.3;
}
// Don't create AudioContext here — no user gesture yet, browser will suspend it.
// Just store the desired volume; initAudio() will apply it when user interacts.
if (savedVol) _pendingVolume = parseFloat(savedVol) || 0.3;
const savedVoice = localStorage.getItem('live-audio-voice');
if (savedVoice) setVoice(savedVoice);
}
+1 -1
View File
@@ -90,7 +90,7 @@
<script src="nodes.js?v=1774126708" onerror="console.error('Failed to load:', this.src)"></script>
<script src="traces.js?v=1774135052" onerror="console.error('Failed to load:', this.src)"></script>
<script src="analytics.js?v=1774126708" onerror="console.error('Failed to load:', this.src)"></script>
<script src="audio.js?v=1774199178" onerror="console.error('Failed to load:', this.src)"></script>
<script src="audio.js?v=1774200342" onerror="console.error('Failed to load:', this.src)"></script>
<script src="audio-v1-constellation.js?v=1774199178" onerror="console.error('Failed to load:', this.src)"></script>
<script src="live.js?v=1774199178" onerror="console.error('Failed to load:', this.src)"></script>
<script src="observers.js?v=1774290000" onerror="console.error('Failed to load:', this.src)"></script>