fix: add delay after AudioContext resume and schedule offset

This commit is contained in:
Mikhail Kiselev
2026-02-10 17:48:34 +03:00
parent 482786a34b
commit 6dac14e0c1
2 changed files with 23 additions and 9 deletions

View File

@@ -46,6 +46,8 @@
// Resume context if suspended (required by browsers on first interaction)
if (ctx.state === 'suspended') {
await ctx.resume()
// Wait a frame for currentTime to update after resume
await new Promise(resolve => setTimeout(resolve, 50))
}
const oscillator = ctx.createOscillator()
const gainNode = ctx.createGain()
@@ -56,11 +58,13 @@
oscillator.frequency.value = frequency
oscillator.type = type
gainNode.gain.setValueAtTime(0.3, ctx.currentTime)
gainNode.gain.exponentialRampToValueAtTime(0.01, ctx.currentTime + duration)
// Use small offset to ensure sound is scheduled in the future
const startTime = ctx.currentTime + 0.01
gainNode.gain.setValueAtTime(0.3, startTime)
gainNode.gain.exponentialRampToValueAtTime(0.01, startTime + duration)
oscillator.start(ctx.currentTime)
oscillator.stop(ctx.currentTime + duration)
oscillator.start(startTime)
oscillator.stop(startTime + duration)
} catch (e) {
console.error('Failed to play sound:', e)
alert('Sound error: ' + e.message)