Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

audioSession.ts

161 lines5.1 KB

1import { AudioModule, setAudioModeAsync, setIsAudioActiveAsync } from "expo-audio";
2​
3type AudioSessionToken = {
4 readonly kind: "playback" | "recording";
5 readonly onCancel?: () => void;
6 readonly onRelease?: () => void;
7 released: boolean;
8};
9​
10let owner: AudioSessionToken | null = null;
11let pending = Promise.resolve();
12​
13// Native session calls are async. Finish an old activation before releasing it
14// or configuring its successor, so it cannot reactivate a released session.
15function enqueue<T>(operation: () => Promise<T>): Promise<T> {
16 const result = pending.then(operation);
17 pending = result.then(
18 () => {},
19 () => {},
20 );
21 return result;
23​
24export function pauseAudioPlayer(player: { pause(deactivateSession?: boolean): void }): void {
25 // Expo Audio otherwise deactivates iOS's shared session 100 ms after pause,
26 // even when a video or recorder has already taken ownership.
27 if (owner && !owner.released) player.pause(false);
28 else player.pause();
30​
31export function disposeAudioPlayer(player: {
32 pause(deactivateSession?: boolean): void;
33 release(): void;
34}): void {
35 void enqueue(async () => {
36 try {
37 pauseAudioPlayer(player);
38 } finally {
39 player.release();
40 }
41 }).catch(() => {});
43​
44export function acquireAudioSession(
45 kind: AudioSessionToken["kind"],
46 onCancel?: () => void,
47 onRelease?: () => void,
48) {
49 const token: AudioSessionToken = { kind, onCancel, onRelease, released: false };
50 if (kind === "playback" && owner?.kind === "recording" && !owner.released) return token;
51 const previous = owner;
52 // Publish before cancelling the old player, including callbacks already queued by Expo.
53 AudioModule.setAudioSessionOwner?.(true);
54 owner = token;
55 if (previous && !previous.released) previous.onCancel?.();
56 return token;
58​
59export function isAudioSessionOwner(token: AudioSessionToken): boolean {
60 return owner === token && !token.released;
62​
63export function activateAudioSession(
64 token: AudioSessionToken,
65 options: { readonly nativePlayback?: boolean; readonly allowBluetoothRecording?: boolean } = {},
66): Promise<boolean> {
67 return enqueue(async () => {
68 if (!isAudioSessionOwner(token)) return false;
69 // Video configures and activates its own native session, including moviePlayback on iOS.
70 if (options.nativePlayback) return true;
71 await setAudioModeAsync({
72 allowsRecording: token.kind === "recording",
73 ...(token.kind === "recording" && options.allowBluetoothRecording === false
74 ? { allowBluetoothRecording: false }
75 : {}),
76 interruptionMode: "doNotMix",
77 playsInSilentMode: true,
78 shouldPlayInBackground: false,
79 });
80 if (!isAudioSessionOwner(token)) return false;
81 await setIsAudioActiveAsync(true);
82 return isAudioSessionOwner(token);
83 });
85​
86export function releaseAudioSession(token: AudioSessionToken): Promise<void> {
87 token.released = true;
88 return enqueue(async () => {
89 if (owner !== token) return;
90 try {
91 if (token.kind === "recording") await setAudioModeAsync({ allowsRecording: false });
92 } finally {
93 if (owner === token) {
94 if (token.kind === "recording") await setIsAudioActiveAsync(false);
95 // Expo pause releases the native session without disabling its global playback gate.
96 // Repeat it after any pending activation, even if playback never started.
97 token.onRelease?.();
98 if (owner === token) {
99 AudioModule.setAudioSessionOwner?.(false);
100 owner = null;
101 }
102 }
103 }
104 });
106​
107export function createAudioPlaybackSession(
108 player: { play(): void; pause(deactivateSession?: boolean): void },
109 nativePlayback = false,
110 onRequestedChange?: (requested: boolean) => void,
111) {
112 let token: AudioSessionToken | null = null;
113 const stopPlayer = () => {
114 // useAudioPlayer/useVideoPlayer may have disposed the native ref during unmount.
115 try {
116 if (nativePlayback) player.pause();
117 else pauseAudioPlayer(player);
118 } catch {}
119 };
120 const pause = () => {
121 const previous = token;
122 token = null;
123 onRequestedChange?.(false);
124 stopPlayer();
125 if (previous) void releaseAudioSession(previous).catch(() => {});
126 };
127 const acquire = () => {
128 const next = acquireAudioSession("playback", pause, stopPlayer);
129 if (!isAudioSessionOwner(next)) {
130 stopPlayer();
131 return null;
132 }
133 token = next;
134 onRequestedChange?.(true);
135 return next;
136 };
137 return {
138 pause,
139 get requested() {
140 return token !== null;
141 },
142 async play(prepare?: () => Promise<void>) {
143 const current = token ?? acquire();
144 if (!current) return;
145 try {
146 await prepare?.();
147 if (!(await activateAudioSession(current, { nativePlayback }))) return;
148 if (token !== current || !isAudioSessionOwner(current)) return;
149 player.play();
150 } catch (error) {
151 if (token === current) pause();
152 throw error;
153 }
154 },
155 // A stopped clock is also reported during buffering and seeks. Native
156 // pause intent must call pause() separately from playingChange.
157 playingChanged(playing: boolean) {
158 if (playing && token === null) acquire();
159 },
160 };