Matthias Nott
2026-03-07 af1543135d42adc2e97dc5243aeef7418cd3b00d
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
import {
  createAudioPlayer,
  requestRecordingPermissionsAsync,
  setAudioModeAsync,
} from "expo-audio";
import * as LegacyFileSystem from "expo-file-system/legacy";
export interface RecordingResult {
  uri: string;
  durationMs: number;
}
let currentPlayer: ReturnType<typeof createAudioPlayer> | null = null;
const playingListeners = new Set<(playing: boolean) => void>();
// Audio queue for chaining sequential voice notes
const audioQueue: Array<{ uri: string; onFinish?: () => void }> = [];
let processingQueue = false;
function notifyListeners(playing: boolean): void {
  for (const cb of playingListeners) cb(playing);
}
export function onPlayingChange(cb: (playing: boolean) => void): () => void {
  playingListeners.add(cb);
  return () => { playingListeners.delete(cb); };
}
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;
}
/**
 * Queue audio for playback. Multiple calls chain sequentially —
 * the next voice note plays only after the current one finishes.
 */
export async function playAudio(
  uri: string,
  onFinish?: () => void
): Promise<void> {
  audioQueue.push({ uri, onFinish });
  if (!processingQueue) {
    processAudioQueue();
  }
}
async function processAudioQueue(): Promise<void> {
  if (processingQueue) return;
  processingQueue = true;
  while (audioQueue.length > 0) {
    const item = audioQueue.shift()!;
    await playOneAudio(item.uri, item.onFinish);
  }
  processingQueue = false;
}
function playOneAudio(uri: string, onFinish?: () => void): Promise<void> {
  return new Promise<void>(async (resolve) => {
    try {
      await setAudioModeAsync({ playsInSilentMode: true });
      const player = createAudioPlayer(uri);
      currentPlayer = player;
      notifyListeners(true);
      player.addListener("playbackStatusUpdate", (status) => {
        if (!status.playing && status.currentTime >= status.duration && status.duration > 0) {
          onFinish?.();
          player.remove();
          if (currentPlayer === player) {
            currentPlayer = null;
            if (audioQueue.length === 0) notifyListeners(false);
          }
          resolve();
        }
      });
      player.play();
    } catch (error) {
      console.error("Failed to play audio:", error);
      resolve();
    }
  });
}
export function isPlaying(): boolean {
  return currentPlayer !== null;
}
/**
 * Stop current playback and clear the queue.
 */
export async function stopPlayback(): Promise<void> {
  audioQueue.length = 0;
  if (currentPlayer) {
    try {
      currentPlayer.pause();
      currentPlayer.remove();
    } catch {
      // Ignore cleanup errors
    }
    currentPlayer = null;
    notifyListeners(false);
  }
}
export async function encodeAudioToBase64(uri: string): Promise<string> {
  const result = await LegacyFileSystem.readAsStringAsync(uri, {
    encoding: LegacyFileSystem.EncodingType.Base64,
  });
  return result;
}