Matthias Nott
2026-03-08 4c266155785aad5050ebff7211e3d5f9e15c3238
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
import React, { useCallback, useRef, useState } from "react";
import { Animated, Pressable, Text, View } from "react-native";
import * as Haptics from "expo-haptics";
import {
  useAudioRecorder,
  RecordingPresets,
  requestRecordingPermissionsAsync,
  setAudioModeAsync,
} from "expo-audio";
import { stopPlayback } from "../../services/audio";
interface VoiceButtonProps {
  onVoiceRecorded: (uri: string, durationMs?: number) => void;
}
const VOICE_BUTTON_SIZE = 72;
/**
 * Tap-to-toggle voice button using expo-audio recording.
 * Records audio and returns the file URI for the caller to send.
 * - Tap once: start recording
 * - Tap again: stop and send
 * - Long-press while recording: cancel (discard)
 */
export function VoiceButton({ onVoiceRecorded }: VoiceButtonProps) {
  const [isRecording, setIsRecording] = useState(false);
  const pulseAnim = useRef(new Animated.Value(1)).current;
  const glowAnim = useRef(new Animated.Value(0)).current;
  const pulseLoop = useRef<Animated.CompositeAnimation | null>(null);
  const recorder = useAudioRecorder(RecordingPresets.HIGH_QUALITY);
  const startPulse = useCallback(() => {
    pulseLoop.current = Animated.loop(
      Animated.sequence([
        Animated.timing(pulseAnim, {
          toValue: 1.15,
          duration: 700,
          useNativeDriver: true,
        }),
        Animated.timing(pulseAnim, {
          toValue: 1,
          duration: 700,
          useNativeDriver: true,
        }),
      ])
    );
    pulseLoop.current.start();
    Animated.timing(glowAnim, {
      toValue: 1,
      duration: 300,
      useNativeDriver: true,
    }).start();
  }, [pulseAnim, glowAnim]);
  const stopPulse = useCallback(() => {
    pulseLoop.current?.stop();
    pulseAnim.setValue(1);
    Animated.timing(glowAnim, {
      toValue: 0,
      duration: 200,
      useNativeDriver: true,
    }).start();
  }, [pulseAnim, glowAnim]);
  const startRecording = useCallback(async () => {
    try {
      await stopPlayback();
      const { granted } = await requestRecordingPermissionsAsync();
      if (!granted) return;
      await setAudioModeAsync({
        allowsRecording: true,
        playsInSilentMode: true,
      });
      startPulse();
      await recorder.prepareToRecordAsync();
      recorder.record();
      setIsRecording(true);
    } catch (err) {
      console.error("Failed to start recording:", err);
      stopPulse();
      setIsRecording(false);
    }
  }, [recorder, startPulse, stopPulse]);
  const stopAndSend = useCallback(async () => {
    stopPulse();
    setIsRecording(false);
    try {
      await recorder.stop();
      // Reset audio mode for playback
      await setAudioModeAsync({
        allowsRecording: false,
        playsInSilentMode: true,
      });
      const uri = recorder.uri;
      if (uri) {
        // currentTime is in seconds after stop
        const durationMs = recorder.currentTime > 0
          ? Math.round(recorder.currentTime * 1000)
          : undefined;
        onVoiceRecorded(uri, durationMs);
      }
    } catch (err) {
      console.error("Failed to stop recording:", err);
    }
  }, [recorder, stopPulse, onVoiceRecorded]);
  const cancelRecording = useCallback(async () => {
    Haptics.notificationAsync(Haptics.NotificationFeedbackType.Warning);
    stopPulse();
    setIsRecording(false);
    try {
      await recorder.stop();
    } catch {
      // ignore
    }
  }, [recorder, stopPulse]);
  const handleTap = useCallback(async () => {
    Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium);
    if (isRecording) {
      await stopAndSend();
    } else {
      await startRecording();
    }
  }, [isRecording, stopAndSend, startRecording]);
  const handleLongPress = useCallback(() => {
    if (isRecording) {
      cancelRecording();
    }
  }, [isRecording, cancelRecording]);
  return (
    <View style={{ alignItems: "center", justifyContent: "center" }}>
      {/* Outer pulse ring */}
      <Animated.View
        style={{
          position: "absolute",
          width: VOICE_BUTTON_SIZE + 24,
          height: VOICE_BUTTON_SIZE + 24,
          borderRadius: (VOICE_BUTTON_SIZE + 24) / 2,
          backgroundColor: isRecording ? "rgba(255, 159, 67, 0.12)" : "transparent",
          transform: [{ scale: pulseAnim }],
          opacity: glowAnim,
        }}
      />
      {/* Button */}
      <Pressable
        onPress={handleTap}
        onLongPress={handleLongPress}
        delayLongPress={600}
      >
        <View
          style={{
            width: VOICE_BUTTON_SIZE,
            height: VOICE_BUTTON_SIZE,
            borderRadius: VOICE_BUTTON_SIZE / 2,
            backgroundColor: isRecording ? "#FF9F43" : "#4A9EFF",
            alignItems: "center",
            justifyContent: "center",
            shadowColor: isRecording ? "#FF9F43" : "#4A9EFF",
            shadowOffset: { width: 0, height: 4 },
            shadowOpacity: 0.4,
            shadowRadius: 12,
            elevation: 8,
          }}
        >
          <Text style={{ fontSize: 28 }}>{isRecording ? "⏹" : "🎤"}</Text>
        </View>
      </Pressable>
      {/* Label */}
      <Text
        style={{
          color: isRecording ? "#FF9F43" : "#5A5A78",
          fontSize: 11,
          marginTop: 4,
          fontWeight: isRecording ? "600" : "400",
        }}
      >
        {isRecording ? "Recording..." : "Tap to talk"}
      </Text>
    </View>
  );
}