|
| 1 | +import React, { useEffect, useRef, useState } from 'react'; |
| 2 | +import { |
| 3 | + Text, |
| 4 | + View, |
| 5 | + StyleSheet, |
| 6 | + TouchableOpacity, |
| 7 | + ScrollView, |
| 8 | + Platform, |
| 9 | +} from 'react-native'; |
| 10 | +import { SafeAreaProvider, SafeAreaView } from 'react-native-safe-area-context'; |
| 11 | +import { useVAD, FSMN_VAD } from 'react-native-executorch'; |
| 12 | +import FontAwesome from '@expo/vector-icons/FontAwesome'; |
| 13 | +import { AudioManager, AudioRecorder } from 'react-native-audio-api'; |
| 14 | +import SWMIcon from '../assets/swm_icon.svg'; |
| 15 | +import DeviceInfo from 'react-native-device-info'; |
| 16 | +import ErrorBanner from '../components/ErrorBanner'; |
| 17 | + |
| 18 | +const isSimulator = DeviceInfo.isEmulatorSync(); |
| 19 | + |
| 20 | +export const VoiceActivityDetectionScreen = ({ |
| 21 | + onBack, |
| 22 | +}: { |
| 23 | + onBack: () => void; |
| 24 | +}) => { |
| 25 | + const model = useVAD({ |
| 26 | + model: FSMN_VAD, |
| 27 | + }); |
| 28 | + |
| 29 | + const [isSpeaking, setIsSpeaking] = useState(false); |
| 30 | + const [error, setError] = useState<string | null>(null); |
| 31 | + const [hasMicPermission, setHasMicPermission] = useState(false); |
| 32 | + const [isStreaming, setIsStreaming] = useState(false); |
| 33 | + |
| 34 | + const recorder = useRef(new AudioRecorder()); |
| 35 | + const logScrollRef = useRef<ScrollView>(null); |
| 36 | + const [logs, setLogs] = useState<string[]>([]); |
| 37 | + |
| 38 | + const addLog = (msg: string) => { |
| 39 | + setLogs((prev) => [...prev, `${new Date().toLocaleTimeString()}: ${msg}`]); |
| 40 | + }; |
| 41 | + |
| 42 | + useEffect(() => { |
| 43 | + AudioManager.setAudioSessionOptions({ |
| 44 | + iosCategory: 'playAndRecord', |
| 45 | + iosMode: 'spokenAudio', |
| 46 | + iosOptions: ['allowBluetoothHFP', 'defaultToSpeaker'], |
| 47 | + }); |
| 48 | + const checkPerms = async () => { |
| 49 | + const status = await AudioManager.requestRecordingPermissions(); |
| 50 | + setHasMicPermission(status === 'Granted'); |
| 51 | + }; |
| 52 | + checkPerms(); |
| 53 | + }, []); |
| 54 | + |
| 55 | + const handleStartStreaming = async () => { |
| 56 | + if (!hasMicPermission) { |
| 57 | + setError('Microphone permission denied. Please enable it in Settings.'); |
| 58 | + return; |
| 59 | + } |
| 60 | + |
| 61 | + setIsStreaming(true); |
| 62 | + setLogs([]); |
| 63 | + addLog('Starting VAD stream...'); |
| 64 | + |
| 65 | + const sampleRate = 16000; |
| 66 | + |
| 67 | + recorder.current.onAudioReady( |
| 68 | + { |
| 69 | + sampleRate, |
| 70 | + bufferLength: 0.1 * sampleRate, |
| 71 | + channelCount: 1, |
| 72 | + }, |
| 73 | + ({ buffer }) => { |
| 74 | + model.streamInsert(buffer.getChannelData(0)); |
| 75 | + } |
| 76 | + ); |
| 77 | + |
| 78 | + try { |
| 79 | + const success = await AudioManager.setAudioSessionActivity(true); |
| 80 | + if (!success) { |
| 81 | + setError('Cannot start audio session correctly'); |
| 82 | + } |
| 83 | + const result = recorder.current.start(); |
| 84 | + if (result.status === 'error') { |
| 85 | + setError(`Recording problems: ${result.status}`); |
| 86 | + } |
| 87 | + |
| 88 | + await model.stream({ |
| 89 | + onSpeechBegin: () => { |
| 90 | + setIsSpeaking(true); |
| 91 | + addLog('Speech detected (Begin)'); |
| 92 | + }, |
| 93 | + onSpeechEnd: () => { |
| 94 | + setIsSpeaking(false); |
| 95 | + addLog('Silence detected (End)'); |
| 96 | + }, |
| 97 | + options: { |
| 98 | + timeout: 100, |
| 99 | + detectionMargin: 300, |
| 100 | + }, |
| 101 | + }); |
| 102 | + } catch (e) { |
| 103 | + setError(e instanceof Error ? e.message : String(e)); |
| 104 | + setIsStreaming(false); |
| 105 | + } |
| 106 | + }; |
| 107 | + |
| 108 | + const handleStopStreaming = () => { |
| 109 | + recorder.current.stop(); |
| 110 | + model.streamStop(); |
| 111 | + setIsStreaming(false); |
| 112 | + setIsSpeaking(false); |
| 113 | + addLog('VAD stream stopped'); |
| 114 | + }; |
| 115 | + |
| 116 | + const getModelStatus = () => { |
| 117 | + if (isStreaming || model.isGenerating) return 'Processing...'; |
| 118 | + if (model.isReady) return 'Ready'; |
| 119 | + return `Loading model: ${(100 * model.downloadProgress).toFixed(2)}%`; |
| 120 | + }; |
| 121 | + |
| 122 | + useEffect(() => { |
| 123 | + if (model.error) setError(String(model.error)); |
| 124 | + }, [model.error]); |
| 125 | + |
| 126 | + const readyToStream = model.isReady; |
| 127 | + const recordingButtonDisabled = |
| 128 | + isSimulator || !readyToStream || model.isGenerating; |
| 129 | + |
| 130 | + return ( |
| 131 | + <SafeAreaProvider> |
| 132 | + <SafeAreaView style={styles.container}> |
| 133 | + <View style={styles.header}> |
| 134 | + <TouchableOpacity style={styles.backButton} onPress={onBack}> |
| 135 | + <FontAwesome name="chevron-left" size={20} color="#0f186e" /> |
| 136 | + </TouchableOpacity> |
| 137 | + <SWMIcon width={60} height={60} /> |
| 138 | + <Text style={styles.headerText}>React Native ExecuTorch</Text> |
| 139 | + <Text style={styles.headerText}>Voice Activity Detection</Text> |
| 140 | + </View> |
| 141 | + |
| 142 | + <View style={styles.statusContainer}> |
| 143 | + <Text>Status: {getModelStatus()}</Text> |
| 144 | + </View> |
| 145 | + |
| 146 | + <ErrorBanner message={error} onDismiss={() => setError(null)} /> |
| 147 | + |
| 148 | + <View style={styles.visualizerContainer}> |
| 149 | + <FontAwesome |
| 150 | + name="volume-up" |
| 151 | + size={100} |
| 152 | + color={ |
| 153 | + isSpeaking ? styles.speakingText.color : styles.silentText.color |
| 154 | + } |
| 155 | + /> |
| 156 | + <Text |
| 157 | + style={[ |
| 158 | + styles.visualizerText, |
| 159 | + isSpeaking ? styles.speakingText : styles.silentText, |
| 160 | + ]} |
| 161 | + > |
| 162 | + {isSpeaking ? 'SPEAKING' : 'SILENT'} |
| 163 | + </Text> |
| 164 | + </View> |
| 165 | + |
| 166 | + <View style={styles.logContainer}> |
| 167 | + <Text style={styles.logLabel}>VAD Events</Text> |
| 168 | + <ScrollView |
| 169 | + ref={logScrollRef} |
| 170 | + style={styles.logScrollContainer} |
| 171 | + onContentSizeChange={() => |
| 172 | + logScrollRef.current?.scrollToEnd({ animated: true }) |
| 173 | + } |
| 174 | + > |
| 175 | + {logs.length > 0 ? ( |
| 176 | + logs.map((log, i) => ( |
| 177 | + <Text key={i} style={styles.logText}> |
| 178 | + {log} |
| 179 | + </Text> |
| 180 | + )) |
| 181 | + ) : ( |
| 182 | + <Text style={styles.placeholderText}> |
| 183 | + No events logged yet... |
| 184 | + </Text> |
| 185 | + )} |
| 186 | + </ScrollView> |
| 187 | + </View> |
| 188 | + |
| 189 | + <View style={styles.inputContainer}> |
| 190 | + {isStreaming ? ( |
| 191 | + <TouchableOpacity |
| 192 | + onPress={handleStopStreaming} |
| 193 | + style={[styles.liveButton, styles.backgroundRed]} |
| 194 | + > |
| 195 | + <FontAwesome name="microphone-slash" size={22} color="white" /> |
| 196 | + <Text style={styles.buttonText}> Stop VAD Stream</Text> |
| 197 | + </TouchableOpacity> |
| 198 | + ) : ( |
| 199 | + <TouchableOpacity |
| 200 | + disabled={recordingButtonDisabled} |
| 201 | + onPress={handleStartStreaming} |
| 202 | + style={[ |
| 203 | + styles.liveButton, |
| 204 | + styles.backgroundBlue, |
| 205 | + recordingButtonDisabled && styles.disabled, |
| 206 | + ]} |
| 207 | + > |
| 208 | + <FontAwesome name="microphone" size={20} color="white" /> |
| 209 | + <Text style={styles.buttonText}> |
| 210 | + {isSimulator |
| 211 | + ? 'Recording not available on Simulator' |
| 212 | + : 'Start VAD Stream'} |
| 213 | + </Text> |
| 214 | + </TouchableOpacity> |
| 215 | + )} |
| 216 | + </View> |
| 217 | + </SafeAreaView> |
| 218 | + </SafeAreaProvider> |
| 219 | + ); |
| 220 | +}; |
| 221 | + |
| 222 | +const styles = StyleSheet.create({ |
| 223 | + container: { |
| 224 | + flex: 1, |
| 225 | + alignItems: 'center', |
| 226 | + backgroundColor: 'white', |
| 227 | + paddingHorizontal: 16, |
| 228 | + }, |
| 229 | + header: { |
| 230 | + alignItems: 'center', |
| 231 | + position: 'relative', |
| 232 | + width: '100%', |
| 233 | + }, |
| 234 | + backButton: { |
| 235 | + position: 'absolute', |
| 236 | + left: 0, |
| 237 | + top: 10, |
| 238 | + padding: 10, |
| 239 | + zIndex: 1, |
| 240 | + }, |
| 241 | + headerText: { |
| 242 | + fontSize: 22, |
| 243 | + fontWeight: 'bold', |
| 244 | + color: '#0f186e', |
| 245 | + }, |
| 246 | + statusContainer: { |
| 247 | + marginTop: 12, |
| 248 | + alignItems: 'center', |
| 249 | + }, |
| 250 | + visualizerContainer: { |
| 251 | + flex: 1, |
| 252 | + justifyContent: 'center', |
| 253 | + alignItems: 'center', |
| 254 | + }, |
| 255 | + visualizerText: { |
| 256 | + marginTop: 20, |
| 257 | + fontSize: 24, |
| 258 | + fontWeight: '800', |
| 259 | + letterSpacing: 2, |
| 260 | + }, |
| 261 | + speakingText: { |
| 262 | + color: '#22c55e', |
| 263 | + }, |
| 264 | + silentText: { |
| 265 | + color: '#ef4444', |
| 266 | + }, |
| 267 | + logContainer: { |
| 268 | + height: 150, |
| 269 | + width: '100%', |
| 270 | + marginVertical: 12, |
| 271 | + }, |
| 272 | + logLabel: { |
| 273 | + marginLeft: 12, |
| 274 | + marginBottom: 4, |
| 275 | + color: '#0f186e', |
| 276 | + fontWeight: '600', |
| 277 | + }, |
| 278 | + logScrollContainer: { |
| 279 | + borderRadius: 12, |
| 280 | + borderWidth: 1, |
| 281 | + borderColor: '#0f186e', |
| 282 | + padding: 12, |
| 283 | + backgroundColor: '#f8fafc', |
| 284 | + }, |
| 285 | + logText: { |
| 286 | + fontSize: 12, |
| 287 | + fontFamily: Platform.OS === 'ios' ? 'Menlo' : 'monospace', |
| 288 | + color: '#334155', |
| 289 | + marginBottom: 2, |
| 290 | + }, |
| 291 | + placeholderText: { |
| 292 | + color: '#aaa', |
| 293 | + fontStyle: 'italic', |
| 294 | + }, |
| 295 | + inputContainer: { |
| 296 | + marginBottom: 30, |
| 297 | + width: '100%', |
| 298 | + }, |
| 299 | + liveButton: { |
| 300 | + flexDirection: 'row', |
| 301 | + justifyContent: 'center', |
| 302 | + alignItems: 'center', |
| 303 | + padding: 16, |
| 304 | + borderRadius: 12, |
| 305 | + gap: 8, |
| 306 | + }, |
| 307 | + backgroundRed: { |
| 308 | + backgroundColor: '#ef4444', |
| 309 | + }, |
| 310 | + backgroundBlue: { |
| 311 | + backgroundColor: '#0f186e', |
| 312 | + }, |
| 313 | + buttonText: { |
| 314 | + color: 'white', |
| 315 | + fontWeight: '600', |
| 316 | + fontSize: 16, |
| 317 | + }, |
| 318 | + disabled: { |
| 319 | + opacity: 0.5, |
| 320 | + }, |
| 321 | +}); |
0 commit comments