Matthias Nott
2026-03-07 d97d98a524d2b2dd56c718a806eecab0b3270c88
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
import {
  createAudioPlayer,
  requestRecordingPermissionsAsync,
  setAudioModeAsync,
} from "expo-audio";
import * as LegacyFileSystem from "expo-file-system/legacy";
import { AppState } from "react-native";
export interface RecordingResult {
  uri: string;
  durationMs: number;
}
// --- Autoplay suppression ---
// Don't autoplay voice messages when the app is in the background
// or when the user is on a phone call (detected via audio interruption).
let _autoplayEnabled = true;
let _audioInterrupted = false;
// Track app state — suppress autoplay when backgrounded
AppState.addEventListener("change", (state) => {
  _autoplayEnabled = state === "active";
});
/** Check if autoplay is safe right now (app in foreground, no interruption). */
export function canAutoplay(): boolean {
  return _autoplayEnabled && !_audioInterrupted;
}
/** Called externally to signal audio interruption (e.g., phone call started/ended). */
export function setAudioInterrupted(interrupted: boolean): void {
  _audioInterrupted = interrupted;
}
// --- Singleton audio player ---
// Only ONE audio can play at a time. Any new play request stops the current one.
let currentPlayer: ReturnType<typeof createAudioPlayer> | null = null;
let currentUri: string | null = null;
let cancelCurrent: (() => void) | null = null;
// Listeners get the URI of what's playing (or null when stopped)
const playingListeners = new Set<(uri: string | null) => void>();
function notifyListeners(uri: string | null): void {
  currentUri = uri;
  for (const cb of playingListeners) cb(uri);
}
/** Subscribe to playing state changes. Returns unsubscribe function. */
export function onPlayingChange(cb: (uri: string | null) => void): () => void {
  playingListeners.add(cb);
  return () => { playingListeners.delete(cb); };
}
/** Get the URI currently playing, or null. */
export function playingUri(): string | null {
  return currentUri;
}
export function isPlaying(): boolean {
  return currentPlayer !== null;
}
export async function requestPermissions(): Promise<boolean> {
  const { status } = await requestRecordingPermissionsAsync();
  return status === "granted";
}
let audioCounter = 0;
/**
 * Convert a base64 audio string to a file URI.
 */
export async function saveBase64Audio(base64: string, ext = "m4a"): Promise<string> {
  const tmpPath = `${LegacyFileSystem.cacheDirectory}pailot-voice-${++audioCounter}.${ext}`;
  await LegacyFileSystem.writeAsStringAsync(tmpPath, base64, {
    encoding: LegacyFileSystem.EncodingType.Base64,
  });
  return tmpPath;
}
// --- Audio queue for chaining sequential voice notes (autoplay) ---
const audioQueue: Array<{ uri: string; onFinish?: () => void }> = [];
let processingQueue = false;
/**
 * Play audio. Stops any current playback first (singleton).
 * Multiple calls chain sequentially via queue (for chunked voice notes).
 */
export async function playAudio(
  uri: string,
  onFinish?: () => void
): Promise<void> {
  audioQueue.push({ uri, onFinish });
  if (!processingQueue) {
    processAudioQueue();
  }
}
/**
 * Play a single audio file, stopping any current playback first.
 * Does NOT queue — immediately replaces whatever is playing.
 */
export async function playSingle(
  uri: string,
  onFinish?: () => void
): Promise<void> {
  await stopPlayback();
  await playOneAudio(uri, onFinish);
}
async function processAudioQueue(): Promise<void> {
  if (processingQueue) return;
  processingQueue = true;
  while (audioQueue.length > 0) {
    const item = audioQueue.shift()!;
    await playOneAudio(item.uri, item.onFinish, false);
  }
  processingQueue = false;
}
function playOneAudio(uri: string, onFinish?: () => void, cancelPrevious = true): Promise<void> {
  return new Promise<void>(async (resolve) => {
    let settled = false;
    const finish = () => {
      if (settled) return;
      settled = true;
      cancelCurrent = null;
      clearTimeout(timer);
      onFinish?.();
      try { player?.pause(); } catch { /* ignore */ }
      try { player?.remove(); } catch { /* ignore */ }
      if (currentPlayer === player) {
        currentPlayer = null;
        notifyListeners(null);
      }
      resolve();
    };
    // Stop any currently playing audio first (only for non-queued calls)
    if (cancelPrevious && cancelCurrent) {
      cancelCurrent();
    }
    // Register cancel callback so stopPlayback can abort us
    cancelCurrent = finish;
    // Safety timeout
    const timer = setTimeout(finish, 5 * 60 * 1000);
    let player: ReturnType<typeof createAudioPlayer> | null = null;
    try {
      await setAudioModeAsync({ playsInSilentMode: true });
      player = createAudioPlayer(uri);
      currentPlayer = player;
      notifyListeners(uri);
      player.addListener("playbackStatusUpdate", (status) => {
        if (!status.playing && status.currentTime > 0) {
          if (status.duration <= 0 || status.currentTime >= status.duration) {
            // Playback finished naturally
            finish();
          } else {
            // Paused mid-playback — likely audio interruption (phone call)
            setAudioInterrupted(true);
          }
        } else if (status.playing && _audioInterrupted) {
          // Resumed after interruption
          setAudioInterrupted(false);
        }
      });
      player.play();
    } catch (error) {
      console.error("Failed to play audio:", error);
      settled = true;
      cancelCurrent = null;
      clearTimeout(timer);
      resolve();
    }
  });
}
/**
 * Stop current playback and clear the queue.
 */
export async function stopPlayback(): Promise<void> {
  audioQueue.length = 0;
  if (cancelCurrent) {
    cancelCurrent();
  } else if (currentPlayer) {
    try {
      currentPlayer.pause();
      currentPlayer.remove();
    } catch {
      // Ignore cleanup errors
    }
    currentPlayer = null;
    notifyListeners(null);
  }
}
export async function encodeAudioToBase64(uri: string): Promise<string> {
  const result = await LegacyFileSystem.readAsStringAsync(uri, {
    encoding: LegacyFileSystem.EncodingType.Base64,
  });
  return result;
}