Skip to content

the ultimate vocal synthesizer - sing, speak, beatbox, and more

Rust

iPhone in silent mode plays nothing: ask iOS for the playback audio session, resume in the tap (#92)

Sasha Patlukhe8b95a37b644
diff --git a/src/audio/AudioEngine.ts b/src/audio/AudioEngine.ts
index 770956f..e4dba23 100644
--- a/src/audio/AudioEngine.ts
+++ b/src/audio/AudioEngine.ts
@@ -4,6 +4,7 @@
*/
import workletUrl from "../worklet/processor.ts?worker&url";
import { chimeraModule } from "../wasm/chimera.ts";
+import { preferPlaybackSession } from "./session.ts";
import type { ToWorklet, FromWorklet, TelemetryMessage, PlannedMessage, CreatureTelemetryMessage } from "../worklet/protocol.ts";
import type { BodyMix } from "../wasm/types.ts";
import type { HumanArtic } from "../wasm/types.ts";
@@ -61,7 +62,11 @@ export class AudioEngine {
// 48 kHz whatever the device runs at (the browser resamples): the airway's cost grows with
// the square of its rate, and a 192 kHz device took ~3x the CPU of 48 kHz and starved the
// worklet (load 120-150%, no sound; issue #33)
+ preferPlaybackSession();
const ctx = new AudioContext({ latencyHint: "interactive", sampleRate: 48000 });
+ // resume now, while the tap that called start() is still the current gesture: iOS Safari
+ // refuses a resume() that comes after the awaits below (the context stays suspended, silent)
+ const resumed = ctx.resume().catch(() => {});
this.ctx = ctx;
this.sampleRate = ctx.sampleRate;
let node: AudioWorkletNode;
@@ -138,6 +143,8 @@ export class AudioEngine {
console.error("worklet:", m.message);
}
};
+ await resumed;
+ // a second chance where the first resume was refused (the result is what callers see)
await ctx.resume();
}
diff --git a/src/audio/session.ts b/src/audio/session.ts
new file mode 100644
index 0000000..0a47fdf
--- /dev/null
+++ b/src/audio/session.ts
@@ -0,0 +1,19 @@
+/**
+ * iOS plays Web Audio in the "ambient" audio session, which the ring/silent switch mutes: on an
+ * iPhone in silent mode the page makes no sound at all, and the volume buttons don't change that.
+ * The "playback" session plays through the switch, like a video or a music app. Safari 16.4+
+ * exposes it as `navigator.audioSession`; elsewhere this does nothing.
+ *
+ * Call it before audio starts (from the tap that starts it).
+ */
+type AudioSessionLike = { type: string };
+
+export function preferPlaybackSession(nav: unknown = typeof navigator === "undefined" ? undefined : navigator): void {
+ const session = (nav as { audioSession?: AudioSessionLike } | undefined)?.audioSession;
+ if (!session || session.type === "playback") return;
+ try {
+ session.type = "playback";
+ } catch {
+ // a browser that refuses: the default session still plays wherever the switch isn't on silent
+ }
+}
diff --git a/src/show/transport.ts b/src/show/transport.ts
index 252787d..0e57e2f 100644
--- a/src/show/transport.ts
+++ b/src/show/transport.ts
@@ -10,6 +10,8 @@
* the source finishes rendering. The context leaving "running" (an iOS interruption, the page
* going to the background), or failing to resume after Play, pauses the transport where it was.
*/
+import { preferPlaybackSession } from "../audio/session.ts";
+
export type TransportState = { playing: boolean; time: number; duration: number; epoch: number };
export class Transport {
@@ -66,6 +68,7 @@ export class Transport {
play(): void {
if (!this.buffer || this.playing) return;
const gen = ++this.generation;
+ preferPlaybackSession();
this.ctx.resume().catch(() => {
// no audio (an interruption, a browser's refusal): back to paused, where it was
if (gen === this.generation && this.playing) this.pause();
diff --git a/tests/audio-session.test.ts b/tests/audio-session.test.ts
new file mode 100644
index 0000000..f9319e0
--- /dev/null
+++ b/tests/audio-session.test.ts
@@ -0,0 +1,65 @@
+/**
+ * iPhone in silent mode: Web Audio in iOS's default "ambient" session is muted by the ring/silent
+ * switch, so Play made no sound whatever the volume. Audio asks for the "playback" session first.
+ */
+import { afterEach, describe, expect, test } from "bun:test";
+import { preferPlaybackSession } from "../src/audio/session.ts";
+import { Transport } from "../src/show/transport.ts";
+
+describe("preferPlaybackSession", () => {
+ test("switches iOS's ambient session to playback, which the silent switch doesn't mute", () => {
+ const nav = { audioSession: { type: "auto" } };
+ preferPlaybackSession(nav);
+ expect(nav.audioSession.type).toBe("playback");
+ });
+
+ test("does nothing where there is no audioSession (every browser but Safari)", () => {
+ expect(() => preferPlaybackSession({})).not.toThrow();
+ expect(() => preferPlaybackSession(undefined)).not.toThrow();
+ });
+
+ test("a browser that refuses the session doesn't stop the audio from starting", () => {
+ const nav = {
+ audioSession: {
+ get type() {
+ return "auto";
+ },
+ set type(_: string) {
+ throw new Error("NotAllowedError");
+ },
+ },
+ };
+ expect(() => preferPlaybackSession(nav)).not.toThrow();
+ });
+});
+
+describe("the duet page's Play", () => {
+ const g = globalThis as { navigator?: unknown };
+ const saved = Object.getOwnPropertyDescriptor(globalThis, "navigator");
+ afterEach(() => {
+ if (saved) Object.defineProperty(globalThis, "navigator", saved);
+ else delete g.navigator;
+ });
+
+ test("asks for the playback session in the tap, before the audio resumes", async () => {
+ const session = { type: "auto" };
+ let typeAtResume = "";
+ Object.defineProperty(globalThis, "navigator", { value: { audioSession: session }, configurable: true });
+ const ctx = {
+ state: "suspended",
+ onstatechange: null,
+ destination: {},
+ currentTime: 0,
+ createBufferSource: () => ({ connect() {}, disconnect() {}, start() {}, stop() {}, onended: null, buffer: null }),
+ decodeAudioData: async () => ({ duration: 10 }),
+ resume: async () => {
+ typeAtResume = session.type;
+ },
+ close: async () => {},
+ };
+ const t = new Transport(ctx as unknown as AudioContext);
+ await t.load(new ArrayBuffer(0));
+ t.play();
+ expect(typeAtResume).toBe("playback");
+ });
+});