Skip to content

Commit 630280c

Browse files
committed
Tweak how we try to start/resume the audio context
Instead of only trying once, keep trying until it starts. Also switch to only listening to pointerdown events, which should work on both desktop and mobile. Helps with Safari on iOS not allowing audio in some cases, and possibly with Firefox too. Fixes #421
1 parent a22674a commit 630280c

1 file changed

Lines changed: 22 additions & 23 deletions

File tree

‎src/emulator/emulator-ui-audio.ts‎

Lines changed: 22 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -68,12 +68,27 @@ export abstract class EmulatorAudio {
6868

6969
// We can't start the audio context until there's a user gesture.
7070
if (this.#audioContext.state === "suspended") {
71-
window.addEventListener("mousedown", this.#resumeOnGesture, {
72-
once: true,
73-
});
74-
window.addEventListener("touchstart", this.#resumeOnGesture, {
75-
once: true,
76-
});
71+
window.addEventListener("pointerdown", this.#resumeOnGesture);
72+
this.#audioContext?.addEventListener(
73+
"statechange",
74+
() => {
75+
if (this.#audioContext?.state === "running") {
76+
window.removeEventListener(
77+
"pointerdown",
78+
this.#resumeOnGesture
79+
);
80+
// Give the audio worklet some time to start processing
81+
// before we signal the emulator to start emitting audio,
82+
// so that the buffer doesn't get too full.
83+
window.setTimeout(
84+
() => this.#handleAudioContextRunning(),
85+
250
86+
);
87+
}
88+
},
89+
{once: true}
90+
);
91+
this.#resumeOnGesture(); // Try resuming anyway, in case we get lucky.
7792
} else {
7893
this.#handleAudioContextRunning();
7994
}
@@ -88,21 +103,6 @@ export abstract class EmulatorAudio {
88103

89104
#resumeOnGesture = () => {
90105
this.#audioContext?.resume();
91-
this.#audioContext?.addEventListener(
92-
"statechange",
93-
() => {
94-
if (this.#audioContext?.state === "running") {
95-
// Give the audio worklet some time to start processing
96-
// before we signal the emulator to start emitting audio,
97-
// so that the buffer doesn't get too full.
98-
window.setTimeout(
99-
() => this.#handleAudioContextRunning(),
100-
250
101-
);
102-
}
103-
},
104-
{once: true}
105-
);
106106
};
107107

108108
#handleAudioContextRunning() {
@@ -112,8 +112,7 @@ export abstract class EmulatorAudio {
112112

113113
stop() {
114114
this.#audioContext?.close();
115-
window.removeEventListener("mousedown", this.#resumeOnGesture);
116-
window.removeEventListener("touchstart", this.#resumeOnGesture);
115+
window.removeEventListener("pointerdown", this.#resumeOnGesture);
117116
if (this.#debugInterval) {
118117
window.clearInterval(this.#debugInterval);
119118
}

0 commit comments

Comments
 (0)