### Run Example Project Source: https://github.com/sgamrekelashvili/expo-audio-studio/blob/main/README.md Navigate to the example directory and install dependencies, then run the project on iOS or Android simulators/devices. ```bash cd example npm install npx expo run:ios # or npx expo run:android # Web support coming soon! ``` -------------------------------- ### Run the Example App Source: https://github.com/sgamrekelashvili/expo-audio-studio/blob/main/CONTRIBUTING.md Navigate to the example directory, install its dependencies, and run the app on iOS or Android. ```bash cd example npm install npx expo run:ios # or npx expo run:android ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/sgamrekelashvili/expo-audio-studio/blob/main/CONTRIBUTING.md Install the necessary Node.js dependencies for the project. ```bash npm install ``` -------------------------------- ### Install Expo Audio Studio Source: https://context7.com/sgamrekelashvili/expo-audio-studio/llms.txt Install the package using npm. This is the first step before configuring permissions. ```bash npm install expo-audio-studio ``` -------------------------------- ### Test Your Changes Source: https://github.com/sgamrekelashvili/expo-audio-studio/blob/main/CONTRIBUTING.md Run build checks and test your changes in the example app on both platforms. ```bash # Run TypeScript checks npm run build # Test in example app cd example npx expo run:ios npx expo run:android ``` -------------------------------- ### Complete Recording Example with VAD Source: https://context7.com/sgamrekelashvili/expo-audio-studio/llms.txt A comprehensive example demonstrating audio recording with Voice Activity Detection (VAD), amplitude monitoring, and playback. It includes requesting permissions, setting up event listeners, configuring VAD, and handling the audio session. ```typescript import ExpoAudioStudio from 'expo-audio-studio'; import { AudioRecordingStateChangeEvent, VoiceActivityEvent, AudioMeteringEvent } from 'expo-audio-studio/types'; import { Platform } from 'react-native'; async function recordWithVAD() { // 1. Request permission const permission = await ExpoAudioStudio.requestMicrophonePermission(); if (!permission.granted) { console.error('Microphone permission denied'); return; } // 2. Set up event listeners const statusSub = ExpoAudioStudio.addListener( 'onRecorderStatusChange', (event: AudioRecordingStateChangeEvent) => { console.log('Status:', event.status); } ); const amplitudeSub = ExpoAudioStudio.addListener( 'onRecorderAmplitude', (event: AudioMeteringEvent) => { const level = Math.max(0, (event.amplitude + 160) / 160); console.log('Level:', (level * 100).toFixed(0) + '%'); } ); const vadSub = ExpoAudioStudio.addListener( 'onVoiceActivityDetected', (event: VoiceActivityEvent) => { if (event.isStateChange) { console.log(event.isVoiceDetected ? 'Speech started' : 'Silence'); } } ); // 3. Configure VAD ExpoAudioStudio.setVADEventMode('onChange'); ExpoAudioStudio.setVoiceActivityThreshold(0.5); ExpoAudioStudio.setVADEnabled(true); // 4. Configure iOS audio session if (Platform.OS === 'ios') { await ExpoAudioStudio.configureAudioSession({ category: 'playAndRecord', mode: 'default', options: { defaultToSpeaker: true, allowBluetooth: true }, }); await ExpoAudioStudio.activateAudioSession(); } // 5. Start recording const path = ExpoAudioStudio.startRecording(); console.log('Recording started:', path); // 6. Record for 10 seconds await new Promise(resolve => setTimeout(resolve, 10000)); // 7. Stop recording const finalPath = ExpoAudioStudio.stopRecording(); console.log('Recording saved:', finalPath); // 8. Get waveform for visualization const waveform = ExpoAudioStudio.getAudioAmplitudes(finalPath, 50); console.log('Waveform bars:', waveform.amplitudes.length); // 9. Play back the recording ExpoAudioStudio.startPlaying(finalPath); // 10. Cleanup statusSub.remove(); amplitudeSub.remove(); vadSub.remove(); ExpoAudioStudio.setVADEnabled(false); } ``` -------------------------------- ### Conventional Commit Examples Source: https://github.com/sgamrekelashvili/expo-audio-studio/blob/main/CONTRIBUTING.md Examples of commit messages following the Conventional Commits specification. ```git feat: add voice activity detection threshold configuration fix: resolve iOS recording permission issue docs: update API documentation for new VAD features ``` -------------------------------- ### Build Project from Source Source: https://github.com/sgamrekelashvili/expo-audio-studio/blob/main/README.md Install project dependencies, build the TypeScript code, and run tests to ensure the project is built correctly from source. ```bash # Install dependencies npm install # Build TypeScript npm run build # Run tests npm test ``` -------------------------------- ### Start Recording to a Custom Directory Source: https://github.com/sgamrekelashvili/expo-audio-studio/blob/main/README.md Initiates audio recording and saves the output to a specified custom directory path. Ensure the directory exists before calling. ```typescript const filePath = startRecording('/path/to/custom/directory'); ``` -------------------------------- ### Configure iOS Audio Session Source: https://context7.com/sgamrekelashvili/expo-audio-studio/llms.txt Configures the iOS audio session for recording and playback. This must be called before starting any audio operations on iOS. ```typescript import ExpoAudioStudio from 'expo-audio-studio'; import { Platform } from 'react-native'; if (Platform.OS === 'ios') { // Configure for recording with playback await ExpoAudioStudio.configureAudioSession({ category: 'playAndRecord', // 'ambient' | 'soloAmbient' | 'playback' | 'record' | 'playAndRecord' | 'multiRoute' mode: 'default', // 'default' | 'voiceChat' | 'gameChat' | 'videoRecording' | 'measurement' | 'moviePlayback' | 'videoChat' | 'spokenAudio' options: { defaultToSpeaker: true, // Output to speaker instead of earpiece allowBluetooth: true, // Allow Bluetooth audio devices allowBluetoothA2DP: true, // Allow Bluetooth A2DP devices mixWithOthers: false, // Mix with other app audio duckOthers: false, // Duck other app audio allowAirPlay: false, // Allow AirPlay }, }); // Activate the session await ExpoAudioStudio.activateAudioSession(); console.log('Audio session configured and activated'); // Start recording or playback ExpoAudioStudio.startRecording(); // When done, deactivate await ExpoAudioStudio.deactivateAudioSession(); } ``` -------------------------------- ### Start and Stop Audio Recording Source: https://context7.com/sgamrekelashvili/expo-audio-studio/llms.txt Initiate audio recording to a WAV file, optionally specifying a custom directory. The recording is saved to the app's cache by default. Listen for status changes during the process. ```typescript import ExpoAudioStudio from 'expo-audio-studio'; import { AudioRecordingStateChangeEvent } from 'expo-audio-studio/types'; // Listen to recording status changes const subscription = ExpoAudioStudio.addListener( 'onRecorderStatusChange', (event: AudioRecordingStateChangeEvent) => { console.log('Recording status:', event.status); // Output: Recording status: recording // Possible values: 'recording' | 'stopped' | 'paused' | 'resumed' | 'failed' | 'error' | 'interrupted' } ); // Start recording (returns file path) const filePath = ExpoAudioStudio.startRecording(); console.log('Recording to:', filePath); // Output: Recording to: /var/mobile/.../recording_1699123456789.wav // Optional: Record to custom directory const customPath = ExpoAudioStudio.startRecording('/path/to/custom/dir/'); // Stop recording (returns final file path) const finalPath = ExpoAudioStudio.stopRecording(); console.log('Recording saved to:', finalPath); // Output: Recording saved to: /var/mobile/.../recording_1699123456789.wav // Cleanup listener subscription.remove(); ``` -------------------------------- ### Configure and Enable Voice Activity Detection (VAD) Source: https://context7.com/sgamrekelashvili/expo-audio-studio/llms.txt Configure VAD event modes and detection thresholds before enabling. VAD automatically activates when recording starts. ```typescript import ExpoAudioStudio from 'expo-audio-studio'; import { VoiceActivityEvent } from 'expo-audio-studio/types'; // Configure VAD event mode before enabling // 'onEveryFrame' - Real-time events (~30 per second) // 'onChange' - Only when voice state changes (battery-friendly) // 'throttled' - Events every X milliseconds ExpoAudioStudio.setVADEventMode('onChange'); // Or with throttle: ExpoAudioStudio.setVADEventMode('throttled', 250); // Set detection threshold (0.0 to 1.0) // Lower = more sensitive (detects quieter speech) // Higher = less sensitive (reduces false positives) ExpoAudioStudio.setVoiceActivityThreshold(0.5); // Enable VAD ExpoAudioStudio.setVADEnabled(true); // Listen to voice activity events const subscription = ExpoAudioStudio.addListener( 'onVoiceActivityDetected', (event: VoiceActivityEvent) => { console.log('Voice detected:', event.isVoiceDetected); console.log('Confidence:', event.confidence); console.log('Event type:', event.eventType); console.log('State changed:', event.isStateChange); // Output: // Voice detected: true // Confidence: 0.85 // Event type: speech_start // State changed: true // eventType values: 'speech_start' | 'speech_continue' | 'silence_start' | 'silence_continue' if (event.eventType === 'speech_start') { console.log('User started talking!'); } else if (event.eventType === 'silence_start') { console.log('User stopped talking'); } } ); // Start recording - VAD automatically activates ExpoAudioStudio.startRecording(); // Check VAD status console.log('VAD enabled:', ExpoAudioStudio.isVADEnabled); // true console.log('VAD active:', ExpoAudioStudio.isVADActive); // true (during recording) // Cleanup subscription.remove(); ExpoAudioStudio.setVADEnabled(false); ``` -------------------------------- ### Request and Check Microphone Permission Source: https://context7.com/sgamrekelashvili/expo-audio-studio/llms.txt Request microphone permission from the user and check the current status. This is essential before starting any audio recording. ```typescript import ExpoAudioStudio from 'expo-audio-studio'; // Request permission const permission = await ExpoAudioStudio.requestMicrophonePermission(); console.log('Permission granted:', permission.granted); // Output: Permission granted: true // Check current status without prompting const status = await ExpoAudioStudio.getMicrophonePermissionStatus(); console.log('Status:', status.status); // 'granted' | 'denied' | 'undetermined' | 'restricted' console.log('Can ask again:', status.canAskAgain); ``` -------------------------------- ### Get Audio Duration Source: https://context7.com/sgamrekelashvili/expo-audio-studio/llms.txt Retrieve the total duration of an audio file in seconds. ```APIDOC ## Get Audio Duration Get the duration of an audio file in seconds. ### Method - **getDuration(filePath: string): number** Returns the duration of the audio file in seconds. ### Request Example ```typescript import ExpoAudioStudio from 'expo-audio-studio'; const duration = ExpoAudioStudio.getDuration('/path/to/audio.wav'); console.log('Duration:', duration, 'seconds'); // Output: Duration: 45.5 seconds // Format for display const formatTime = (seconds: number): string => { const mins = Math.floor(seconds / 60); const secs = Math.floor(seconds % 60); return `${mins}:${secs.toString().padStart(2, '0')}`; }; console.log('Formatted:', formatTime(duration)); // Output: Formatted: 0:45 ``` ``` -------------------------------- ### Get Last Recording Source: https://context7.com/sgamrekelashvili/expo-audio-studio/llms.txt Retrieve the file path of the most recently made audio recording. ```APIDOC ## Get Last Recording Get the file path of the most recent recording. ### Method - **lastRecording(): string | null** Returns the file path of the last recording, or `null` if no recordings are found. ### Request Example ```typescript import ExpoAudioStudio from 'expo-audio-studio'; const lastFile = ExpoAudioStudio.lastRecording(); if (lastFile) { console.log('Last recording:', lastFile); // Output: Last recording: /var/mobile/.../recording_1699123456789.wav // Play it ExpoAudioStudio.startPlaying(lastFile); } else { console.log('No recordings found'); } ``` ``` -------------------------------- ### Get Waveform Amplitudes Source: https://context7.com/sgamrekelashvili/expo-audio-studio/llms.txt Analyze an audio file to obtain amplitude data, suitable for waveform visualization. ```APIDOC ## Get Waveform Amplitudes Analyze an audio file and get amplitude data for waveform visualization. ### Method - **getAudioAmplitudes(filePath: string, numberOfBars: number): { success: boolean; barsCount?: number; duration?: number; sampleRate?: number; amplitudes?: number[]; error?: string }** Analyzes the audio file and returns an object containing analysis results. - `success` (boolean): Indicates if the analysis was successful. - `barsCount` (number, optional): The number of amplitude bars generated. - `duration` (number, optional): The duration of the audio file in seconds. - `sampleRate` (number, optional): The sample rate of the audio file in Hz. - `amplitudes` (array of numbers, optional): An array of amplitude values (in dB). - `error` (string, optional): An error message if the analysis failed. ### Request Example ```typescript import ExpoAudioStudio from 'expo-audio-studio'; // Get amplitude data for visualization (100 bars) const result = ExpoAudioStudio.getAudioAmplitudes('/path/to/audio.wav', 100); if (result.success) { console.log('Bars count:', result.barsCount); console.log('Duration:', result.duration, 'seconds'); console.log('Sample rate:', result.sampleRate, 'Hz'); console.log('Amplitudes (dB):', result.amplitudes.slice(0, 5)); // Output: // Bars count: 100 // Duration: 45.5 seconds // Sample rate: 16000 Hz // Amplitudes (dB): [-35.2, -28.7, -42.1, -31.5, -38.9] // Normalize amplitudes for UI visualization (dB to 0-1 range) const normalized = result.amplitudes.map(dB => Math.max(0, (dB + 60) / 60) ); console.log('Normalized:', normalized.slice(0, 5)); // Output: Normalized: [0.41, 0.52, 0.30, 0.48, 0.35] } else { console.error('Analysis failed:', result.error); } ``` ``` -------------------------------- ### Playback Speed and Seeking Source: https://context7.com/sgamrekelashvili/expo-audio-studio/llms.txt Control playback speed and seek to specific positions in audio files. You can also prepare the player for seeking before starting playback. ```APIDOC ## Playback Speed and Seeking Control playback speed and seek to specific positions in audio. ### Methods - **startPlaying(filePath: string): void** Starts playback of the audio file at the specified path. - **setPlaybackSpeed(speed: string): void** Sets the playback speed of the audio. Accepted values are "0.5", "1.0", "1.5", "2.0". - **seekTo(positionInSeconds: number): string** Seeks to a specific position in the audio file (in seconds). Returns "success" on completion. - **preparePlayer(filePath: string): void** Prepares the audio player for a given file without starting playback. Useful for seeking before playback. - **resumePlayer(): void** Resumes playback after preparing the player or pausing. ### Request Example ```typescript import ExpoAudioStudio from 'expo-audio-studio'; // Start playback ExpoAudioStudio.startPlaying('/path/to/audio.wav'); // Set playback speed (0.5 to 2.0) ExpoAudioStudio.setPlaybackSpeed('0.5'); // Half speed ExpoAudioStudio.setPlaybackSpeed('1.5'); // 1.5x speed ExpoAudioStudio.setPlaybackSpeed('2.0'); // Double speed // Seek to position (in seconds) const seekResult = ExpoAudioStudio.seekTo(30.5); console.log(seekResult); // Output: "success" // Prepare player without starting (useful for seeking before playback) ExpoAudioStudio.preparePlayer('/path/to/audio.wav'); ExpoAudioStudio.seekTo(10.0); ExpoAudioStudio.resumePlayer(); // Start from 10 seconds ``` ``` -------------------------------- ### Control Playback Speed and Seek Source: https://context7.com/sgamrekelashvili/expo-audio-studio/llms.txt Adjust playback speed between 0.5x and 2.0x. Seek to precise timestamps in seconds. Use preparePlayer to set a starting point before resuming playback. ```typescript import ExpoAudioStudio from 'expo-audio-studio'; // Start playback ExpoAudioStudio.startPlaying('/path/to/audio.wav'); // Set playback speed (0.5 to 2.0) ExpoAudioStudio.setPlaybackSpeed('0.5'); // Half speed ExpoAudioStudio.setPlaybackSpeed('1.5'); // 1.5x speed ExpoAudioStudio.setPlaybackSpeed('2.0'); // Double speed // Seek to position (in seconds) const seekResult = ExpoAudioStudio.seekTo(30.5); console.log(seekResult); // Output: "success" // Prepare player without starting (useful for seeking before playback) ExpoAudioStudio.preparePlayer('/path/to/audio.wav'); ExpoAudioStudio.seekTo(10.0); ExpoAudioStudio.resumePlayer(); // Start from 10 seconds ``` -------------------------------- ### Audio Analysis API Source: https://github.com/sgamrekelashvili/expo-audio-studio/blob/main/README.md APIs for analyzing audio files, such as getting waveform data and duration. ```APIDOC ## getAudioAmplitudes ### Description Retrieves audio amplitude data for a given audio file. ### Method `getAudioAmplitudes(filePath, numberOfPoints)` ### Parameters #### Path Parameters - **filePath** (string) - Required - The path to the audio file. - **numberOfPoints** (number) - Required - The number of amplitude data points to generate. ### Returns - **object** - An object containing amplitude data. - **amplitudes** (array of numbers) - The amplitude values (in dB). ## getDuration ### Description Gets the duration of an audio file. ### Method `getDuration(filePath)` ### Parameters #### Path Parameters - **filePath** (string) - Required - The path to the audio file. ### Returns - **number** - The duration of the audio file in seconds. ``` -------------------------------- ### Audio Recording Functions Source: https://github.com/sgamrekelashvili/expo-audio-studio/blob/main/README.md Functions for controlling the audio recording process, including starting, stopping, pausing, resuming, and managing real-time audio chunk capture. ```APIDOC ## Recording Functions ### `startRecording(directoryPath?)` **Description**: Start audio recording. **Method**: N/A (Function Call) **Parameters**: #### Path Parameters - **directoryPath** (string) - Optional - The directory path to save the recording. **Returns**: - `string` - File path of the recording. ``` ```APIDOC ### `stopRecording()` **Description**: Stop recording. **Method**: N/A (Function Call) **Returns**: - `string` - Final file path of the recording. ``` ```APIDOC ### `pauseRecording()` **Description**: Pause recording. **Method**: N/A (Function Call) **Returns**: - `string` - Status message. ``` ```APIDOC ### `resumeRecording()` **Description**: Resume recording. **Method**: N/A (Function Call) **Returns**: - `string` - Status message. ``` ```APIDOC ### `setListenToChunks(enabled)` **Description**: Enable or disable real-time audio chunk capture. **Method**: N/A (Function Call) **Parameters**: #### Query Parameters - **enabled** (boolean) - Required - Whether to enable chunk listening. **Returns**: - `boolean` - The enabled state. ``` ```APIDOC ### `lastRecording()` **Description**: Get the path of the last recording. **Method**: N/A (Function Call) **Returns**: - `string` or `null` - The path of the last recording or null if no recording exists. ``` -------------------------------- ### Audio Analysis Functions Source: https://github.com/sgamrekelashvili/expo-audio-studio/blob/main/README.md Functions for analyzing audio files, such as getting duration and waveform data. ```APIDOC ## Audio Analysis ### `getDuration(uri)` **Description**: Get the duration of an audio file. **Method**: N/A (Function Call) **Parameters**: #### Path Parameters - **uri** (string) - Required - The URI of the audio file. **Returns**: - `number` - Duration in seconds. ``` ```APIDOC ### `getAudioAmplitudes(fileUrl, barsCount)` **Description**: Get waveform data (dB values) for an audio file. **Method**: N/A (Function Call) **Parameters**: #### Query Parameters - **fileUrl** (string) - Required - The URL of the audio file. - **barsCount** (number) - Required - The number of bars (data points) to generate. **Returns**: - `object` - Amplitude data. ``` ```APIDOC ### `setAmplitudeUpdateFrequency(hz)` **Description**: Set the update frequency for amplitude data. **Method**: N/A (Function Call) **Parameters**: #### Query Parameters - **hz** (number) - Required - The update frequency in Hertz. **Returns**: - `string` - Status message. ``` -------------------------------- ### Audio Playback Functions Source: https://github.com/sgamrekelashvili/expo-audio-studio/blob/main/README.md Functions for controlling audio playback, including starting, stopping, pausing, resuming, setting playback speed, and seeking to a specific position. ```APIDOC ## Playback Functions ### `startPlaying(path)` **Description**: Start audio playback from a given file path. **Method**: N/A (Function Call) **Parameters**: #### Path Parameters - **path** (string) - Required - The path to the audio file to play. **Returns**: - `string` - Status message. ``` ```APIDOC ### `stopPlayer()` **Description**: Stop the current audio playback. **Method**: N/A (Function Call) **Returns**: - `string` - Status message. ``` ```APIDOC ### `pausePlayer()` **Description**: Pause the current audio playback. **Method**: N/A (Function Call) **Returns**: - `string` - Status message. ``` ```APIDOC ### `resumePlayer()` **Description**: Resume the paused audio playback. **Method**: N/A (Function Call) **Returns**: - `string` - Status message. ``` ```APIDOC ### `setPlaybackSpeed(speed)` **Description**: Set the playback speed for the audio. **Method**: N/A (Function Call) **Parameters**: #### Query Parameters - **speed** (string) - Required - The desired playback speed (e.g., '0.5', '1.5', '2.0'). **Returns**: - `string` - Status message. ``` ```APIDOC ### `seekTo(position)` **Description**: Seek to a specific position in the audio playback. **Method**: N/A (Function Call) **Parameters**: #### Query Parameters - **position** (number) - Required - The position in seconds to seek to. **Returns**: - `string` - Status message. ``` -------------------------------- ### Play Audio File with Playback Control Source: https://github.com/sgamrekelashvili/expo-audio-studio/blob/main/README.md Start playback of an audio file and listen to status changes. Playback speed can be adjusted dynamically. Remember to remove the listener when playback is no longer needed. ```typescript import ExpoAudioStudio from 'expo-audio-studio'; // Listen to playback events const playerSubscription = ExpoAudioStudio.addListener( 'onPlayerStatusChange', (event: PlayerStatusChangeEvent) => { console.log('Playing:', event.isPlaying); } ); // Start playback ExpoAudioStudio.startPlaying('/path/to/audio/file.wav'); // Control playback speed ExpoAudioStudio.setPlaybackSpeed('1.5'); // 1.5x speed // Cleanup playerSubscription.remove(); ``` -------------------------------- ### Listen to Recorder Amplitude Source: https://github.com/sgamrekelashvili/expo-audio-studio/blob/main/README.md Subscribe to audio metering events to get the current amplitude (dB level) of the recording. This is useful for visualizing audio input. ```typescript import ExpoAudioStudio from 'expo-audio-studio'; const subscription = ExpoAudioStudio.addListener( 'onRecorderAmplitude', (event: AudioMeteringEvent) => { // event.amplitude: number (dB level) } ); ``` -------------------------------- ### Control Audio Playback Source: https://context7.com/sgamrekelashvili/expo-audio-studio/llms.txt Manage audio playback including starting, pausing, resuming, and stopping audio files. Listen to player status changes to track playback progress. ```typescript import ExpoAudioStudio from 'expo-audio-studio'; import { PlayerStatusChangeEvent } from 'expo-audio-studio/types'; // Listen to playback events const subscription = ExpoAudioStudio.addListener( 'onPlayerStatusChange', (event: PlayerStatusChangeEvent) => { console.log('Is playing:', event.isPlaying); console.log('Did finish:', event.didJustFinish); // Output: // Is playing: true // Did finish: false } ); // Start playback const result = ExpoAudioStudio.startPlaying('/path/to/audio.wav'); console.log(result); // Output: "playing" // Pause playback ExpoAudioStudio.pausePlayer(); // Resume playback ExpoAudioStudio.resumePlayer(); // Stop playback ExpoAudioStudio.stopPlayer(); // Get player status const status = ExpoAudioStudio.playerStatus; console.log('Status:', status); // Output: { isPlaying: true, currentTime: 15.5, duration: 60.0, speed: 1.0 } // Get current position const position = ExpoAudioStudio.currentPosition; console.log('Position:', position, 'seconds'); // Output: Position: 15.5 seconds // Cleanup subscription.remove(); ``` -------------------------------- ### Get Audio Duration Source: https://context7.com/sgamrekelashvili/expo-audio-studio/llms.txt Retrieve the total duration of an audio file in seconds. Includes a utility function to format seconds into minutes and seconds for display. ```typescript import ExpoAudioStudio from 'expo-audio-studio'; const duration = ExpoAudioStudio.getDuration('/path/to/audio.wav'); console.log('Duration:', duration, 'seconds'); // Output: Duration: 45.5 seconds // Format for display const formatTime = (seconds: number): string => { const mins = Math.floor(seconds / 60); const secs = Math.floor(seconds % 60); return `${mins}:${secs.toString().padStart(2, '0')}`; }; console.log('Formatted:', formatTime(duration)); // Output: Formatted: 0:45 ``` -------------------------------- ### Voice-Activated Recording (Throttled Events) Source: https://github.com/sgamrekelashvili/expo-audio-studio/blob/main/README.md Configure voice activity detection to send events at a specified interval (e.g., every 250ms) using the 'throttled' mode. This example logs whether voice or silence is detected. ```typescript import ExpoAudioStudio from 'expo-audio-studio'; // Only notify in every 250ms ExpoAudioStudio.setVADEventMode('throttled', 250); ExpoAudioStudio.setVADEnabled(true); const subscription = ExpoAudioStudio.addListener( 'onVoiceActivityDetected', (event: VoiceActivityEvent) => { if (event.isVoiceDetected) { console.log('Voice detected'); } else { console.log('Silence detected'); } } ); ``` -------------------------------- ### Get Last Recording Path Source: https://context7.com/sgamrekelashvili/expo-audio-studio/llms.txt Retrieve the file path of the most recently recorded audio file. If no recordings exist, it returns null. The retrieved path can be used to play the recording. ```typescript import ExpoAudioStudio from 'expo-audio-studio'; const lastFile = ExpoAudioStudio.lastRecording(); if (lastFile) { console.log('Last recording:', lastFile); // Output: Last recording: /var/mobile/.../recording_1699123456789.wav // Play it ExpoAudioStudio.startPlaying(lastFile); } else { console.log('No recordings found'); } ``` -------------------------------- ### Get Waveform Data and Duration Source: https://github.com/sgamrekelashvili/expo-audio-studio/blob/main/README.md Retrieve audio amplitude data for waveform visualization and the duration of an audio file. Amplitudes are returned in dB and can be normalized to a 0-1 range for UI display. ```typescript const waveformData = ExpoAudioStudio.getAudioAmplitudes( '/path/to/file.wav', 100 ); console.log('Amplitude values:', waveformData.amplitudes); // Normalize for UI visualization (dB to 0-1 range) const normalized = waveformData.amplitudes.map(dB => Math.max(0, (dB + 60) / 60) ); const duration = ExpoAudioStudio.getDuration('/path/to/file.wav'); ``` -------------------------------- ### Build Development App Source: https://github.com/sgamrekelashvili/expo-audio-studio/blob/main/README.md Prebuild your app and create a development build to apply native code changes. This is necessary because the library uses native code. ```bash # Prebuild to apply the plugin npx expo prebuild # Create development build npx expo run:ios npx expo run:android ``` -------------------------------- ### Clone the Repository Source: https://github.com/sgamrekelashvili/expo-audio-studio/blob/main/CONTRIBUTING.md Clone the Expo Audio Studio repository to your local machine. Replace YOUR_USERNAME with your GitHub username. ```bash git clone https://github.com/YOUR_USERNAME/expo-audio-studio.git cd expo-audio-studio ``` -------------------------------- ### Contribute to Project Source: https://github.com/sgamrekelashvili/expo-audio-studio/blob/main/README.md Follow these steps to contribute to the project: fork the repository, create a new branch for your feature, make changes, and open a pull request. ```git # Fork the repo # Create a branch: git checkout -b feature/my-feature # Make your changes # Push and open a pull request ``` -------------------------------- ### Capture Audio Chunks in Real-time Source: https://github.com/sgamrekelashvili/expo-audio-studio/blob/main/README.md Enable chunk listening to receive raw PCM audio data as it's recorded. Store these chunks for later processing, such as decoding and adding a WAV header. Ensure to remove the listener and disable chunk listening when done. ```typescript import ExpoAudioStudio from 'expo-audio-studio'; import { encode as base64Encode, decode as base64Decode } from 'base-64'; // Enable chunk listening (disabled by default) ExpoAudioStudio.setListenToChunks(true); // Store chunks as they arrive const audioChunks: string[] = []; // Listen to audio chunks during recording const chunkSubscription = ExpoAudioStudio.addListener( 'onAudioChunk', (event: AudioChunkEvent) => { // event.base64 contains raw PCM audio data (Int16, 16kHz, mono) audioChunks.push(event.base64); console.log('Received chunk, total:', audioChunks.length); } ); // Start recording - chunks will be sent in real-time ExpoAudioStudio.startRecording(); // Later, when stopping... ExpoAudioStudio.stopRecording(); // Process the chunks - decode, concatenate, add WAV header, etc. // See example/components/ChunkRecorder.tsx for full implementation // Cleanup chunkSubscription.remove(); ExpoAudioStudio.setListenToChunks(false); ``` -------------------------------- ### Stage and Commit Changes Source: https://github.com/sgamrekelashvili/expo-audio-studio/blob/main/CONTRIBUTING.md Stage all changes and commit them with a descriptive message following Conventional Commits. ```bash git add . git commit -m "feat: add amazing new feature" ``` -------------------------------- ### Update Changelog Source: https://github.com/sgamrekelashvili/expo-audio-studio/blob/main/CONTRIBUTING.md Document your changes in the CHANGELOG.md file using the provided Markdown format. ```markdown ## [Unreleased] ### Added - New voice activity detection threshold configuration ### Fixed - iOS recording permission issue ### Changed - Improved error handling in playback functions ``` -------------------------------- ### Audio Session Configuration API Source: https://github.com/sgamrekelashvili/expo-audio-studio/blob/main/README.md APIs for configuring and managing the audio session, essential for audio playback and recording. ```APIDOC ## configureAudioSession ### Description Configures the audio session with specified category, mode, and options. ### Method `configureAudioSession(options)` ### Parameters #### Request Body - **options** (object) - Required - Configuration options for the audio session. - **category** (string) - Required - The audio category (e.g., 'playAndRecord', 'playback', 'record'). - **mode** (string) - Optional - The audio mode (e.g., 'default', 'voiceChat'). - **options** (object) - Optional - Additional options. - **defaultToSpeaker** (boolean) - Optional - Whether to default to speakerphone. - **allowBluetooth** (boolean) - Optional - Whether to allow Bluetooth audio routing. ### Request Example ```json { "category": "playAndRecord", "mode": "default", "options": { "defaultToSpeaker": true, "allowBluetooth": true } } ``` ## activateAudioSession ### Description Activates the audio session, making it ready for audio operations. ### Method `activateAudioSession()` ### Returns - **Promise** - A promise that resolves when the audio session is activated. ``` -------------------------------- ### Constants Source: https://github.com/sgamrekelashvili/expo-audio-studio/blob/main/README.md Available constants providing real-time information about audio playback and recording. ```APIDOC ## Constants - **`currentPosition`**: Current playback position in seconds (`number`). - **`meterLevel`**: Current audio level during recording in dB (`number`). - **`playerStatus`**: Detailed player status information (`object`). - **`isVADActive`**: Whether VAD is currently active (`boolean`). - **`isVADEnabled`**: Whether VAD is enabled by user preference (`boolean`). ``` -------------------------------- ### Record Audio in Expo Source: https://github.com/sgamrekelashvili/expo-audio-studio/blob/main/README.md Record audio using Expo Audio Studio. Remember to request microphone permission first and clean up the listener subscription after use. ```typescript import ExpoAudioStudio from 'expo-audio-studio'; // Request permission first const permission = await ExpoAudioStudio.requestMicrophonePermission(); if (!permission.granted) { console.log('Microphone permission denied'); return; } // Listen to recording events const subscription = ExpoAudioStudio.addListener( 'onRecorderStatusChange', (event: AudioRecordingStateChangeEvent) => { console.log('Recording status:', event.status); } ); // Start recording const filePath = ExpoAudioStudio.startRecording(); console.log('Recording to:', filePath); // Stop recording const finalPath = ExpoAudioStudio.stopRecording(); console.log('Recording saved to:', finalPath); // Cleanup subscription.remove(); ``` -------------------------------- ### Configure and Activate iOS Audio Session Source: https://github.com/sgamrekelashvili/expo-audio-studio/blob/main/README.md Configures the audio session for iOS, specifying category, mode, and options. It's crucial not to reconfigure the audio session while recording or playing to avoid app freezes. Activate the session afterwards. ```typescript import ExpoAudioStudio from 'expo-audio-studio'; await ExpoAudioStudio.configureAudioSession({ category: 'playAndRecord', mode: 'default', options: { defaultToSpeaker: true, allowBluetooth: true, }, }); await ExpoAudioStudio.activateAudioSession(); ``` -------------------------------- ### Configure Microphone Permissions Source: https://github.com/sgamrekelashvili/expo-audio-studio/blob/main/README.md Add the plugin to your app.config.ts to automatically configure microphone permissions. This ensures your app can access the microphone for audio recording. ```typescript export default { plugins: [ [ 'expo-audio-studio', { microphonePermission: 'Allow $(PRODUCT_NAME) to access your microphone for audio recording', }, ], ], }; ``` ```typescript export default { plugins: ['expo-audio-studio'], }; ``` -------------------------------- ### List Audio Recordings Source: https://context7.com/sgamrekelashvili/expo-audio-studio/llms.txt List all audio recordings, either in the default cache directory or a custom specified directory. Each recording entry includes name, path, size, duration, and last modified timestamp. ```typescript import ExpoAudioStudio from 'expo-audio-studio'; // List recordings in default cache directory const recordings = ExpoAudioStudio.listRecordings(); // List recordings in custom directory const customRecordings = ExpoAudioStudio.listRecordings('/path/to/custom/dir/'); recordings.forEach(file => { console.log('File:', file.name); console.log('Path:', file.path); console.log('Size:', file.size, 'bytes'); console.log('Duration:', file.duration, 'seconds'); console.log('Modified:', new Date(file.lastModified)); // Output: // File: recording_1699123456789.wav // Path: /var/mobile/.../recording_1699123456789.wav // Size: 1440044 bytes // Duration: 45.0 seconds // Modified: Sat Nov 04 2023 15:30:56 }); ``` -------------------------------- ### Create a Feature Branch Source: https://github.com/sgamrekelashvili/expo-audio-studio/blob/main/CONTRIBUTING.md Before making changes, create a new branch for your feature. ```bash git checkout -b feature/your-feature-name ``` -------------------------------- ### Configure Expo Audio Studio Plugin Source: https://context7.com/sgamrekelashvili/expo-audio-studio/llms.txt Add the plugin configuration to your app.config.ts file to set microphone permission messages. ```typescript export default { plugins: [ [ 'expo-audio-studio', { microphonePermission: 'Allow $(PRODUCT_NAME) to access your microphone for audio recording', }, ], ], }; ``` -------------------------------- ### List Recordings Source: https://context7.com/sgamrekelashvili/expo-audio-studio/llms.txt List all audio recordings stored in a specified directory. ```APIDOC ## List Recordings List all audio recordings in a directory. ### Method - **listRecordings(directoryPath?: string): Array<{ name: string; path: string; size: number; duration: number; lastModified: number }>** Lists audio files. If no path is provided, it defaults to the cache directory. - `name` (string): The name of the audio file. - `path` (string): The full path to the audio file. - `size` (number): The size of the file in bytes. - `duration` (number): The duration of the audio file in seconds. - `lastModified` (number): The last modified timestamp of the file. ### Request Example ```typescript import ExpoAudioStudio from 'expo-audio-studio'; // List recordings in default cache directory const recordings = ExpoAudioStudio.listRecordings(); // List recordings in custom directory const customRecordings = ExpoAudioStudio.listRecordings('/path/to/custom/dir/'); recordings.forEach(file => { console.log('File:', file.name); console.log('Path:', file.path); console.log('Size:', file.size, 'bytes'); console.log('Duration:', file.duration, 'seconds'); console.log('Modified:', new Date(file.lastModified)); // Output: // File: recording_1699123456789.wav // Path: /var/mobile/.../recording_1699123456789.wav // Size: 1440044 bytes // Duration: 45.0 seconds // Modified: Sat Nov 04 2023 15:30:56 }); ``` ``` -------------------------------- ### Join Audio Files Source: https://context7.com/sgamrekelashvili/expo-audio-studio/llms.txt Concatenate multiple audio files into a single output file. ```APIDOC ## Join Audio Files Concatenate multiple audio files into a single file. ### Method - **joinAudioFiles(inputFiles: string[], outputPath: string): string** Joins the audio files specified in `inputFiles` and saves the result to `outputPath`. Returns the output path on success or an error message string. ### Request Example ```typescript import ExpoAudioStudio from 'expo-audio-studio'; const inputFiles = [ '/path/to/recording1.wav', '/path/to/recording2.wav', '/path/to/recording3.wav', ]; const outputPath = '/path/to/joined_audio.wav'; const result = ExpoAudioStudio.joinAudioFiles(inputFiles, outputPath); if (!result.startsWith('Error:')) { console.log('Files joined successfully:', result); // Output: Files joined successfully: /path/to/joined_audio.wav // Play the joined file ExpoAudioStudio.startPlaying(result); } else { console.error('Join failed:', result); } ``` ``` -------------------------------- ### Run Automated Tests Source: https://github.com/sgamrekelashvili/expo-audio-studio/blob/main/CONTRIBUTING.md Execute automated tests, including unit tests, linting, and type checking. ```bash # Run TypeScript tests npm test # Run linting npm run lint # Type checking npm run type-check ``` -------------------------------- ### File Management API Source: https://github.com/sgamrekelashvili/expo-audio-studio/blob/main/README.md APIs for managing audio recordings, including listing and joining files. ```APIDOC ## listRecordings ### Description Lists all audio files in the specified directory. ### Method `listRecordings(directoryPath?)` ### Parameters #### Query Parameters - **directoryPath** (string) - Optional - The path to the directory to list recordings from. Defaults to the app's recording directory. ### Returns - **array** - A list of file paths for the audio recordings. ## joinAudioFiles ### Description Concatenates multiple audio files into a single output file. ### Method `joinAudioFiles(filePaths, outputPath)` ### Parameters #### Path Parameters - **filePaths** (array of strings) - Required - An array of paths to the audio files to be joined. - **outputPath** (string) - Required - The path where the concatenated audio file will be saved. ### Returns - **string** - The output path of the newly created joined audio file. ``` -------------------------------- ### Capture Real-time Audio Chunks Source: https://context7.com/sgamrekelashvili/expo-audio-studio/llms.txt Enable chunk listening to capture audio data in real-time as base64-encoded PCM chunks during recording. Process these chunks after stopping the recording. ```typescript import ExpoAudioStudio from 'expo-audio-studio'; import { AudioChunkEvent } from 'expo-audio-studio/types'; // Store chunks const audioChunks: string[] = []; // Enable chunk listening (disabled by default) ExpoAudioStudio.setListenToChunks(true); // Listen to audio chunks const subscription = ExpoAudioStudio.addListener( 'onAudioChunk', (event: AudioChunkEvent) => { // event.base64 contains raw PCM audio data (Int16, 16kHz, mono) audioChunks.push(event.base64); console.log('Received chunk #', audioChunks.length); // Output: Received chunk # 1 } ); // Start recording - chunks stream in real-time ExpoAudioStudio.startRecording(); // ... recording ... // Stop and process chunks ExpoAudioStudio.stopRecording(); console.log('Total chunks:', audioChunks.length); // Output: Total chunks: 150 // Process chunks - decode base64 and add WAV header // See ChunkRecorder.tsx example for full implementation // Cleanup subscription.remove(); ExpoAudioStudio.setListenToChunks(false); ``` -------------------------------- ### Join Multiple Audio Files Source: https://github.com/sgamrekelashvili/expo-audio-studio/blob/main/README.md Concatenate multiple audio files into a single output file. Provide an array of input file paths and the desired output path. ```typescript const inputFiles = [ '/path/to/file1.wav', '/path/to/file2.wav', '/path/to/file3.wav', ]; const outputPath = '/path/to/joined_audio.wav'; const result = ExpoAudioStudio.joinAudioFiles(inputFiles, outputPath); console.log('Joined file created:', result); ``` -------------------------------- ### Voice-Activated Recording (State Change Events) Source: https://github.com/sgamrekelashvili/expo-audio-studio/blob/main/README.md Implement voice-activated recording by listening for 'speech_start' and 'silence_start' events. Configure VAD to only notify on state changes for battery efficiency. ```typescript import ExpoAudioStudio from 'expo-audio-studio'; // Only notify on state changes for battery efficiency ExpoAudioStudio.setVADEventMode('onChange'); ExpoAudioStudio.setVADEnabled(true); const subscription = ExpoAudioStudio.addListener( 'onVoiceActivityDetected', (event: VoiceActivityEvent) => { if (event.eventType === 'speech_start') { console.log('🎤 Voice detected'); } else if (event.eventType === 'silence_start') { console.log('🔇 Silence detected'); } } ); ``` -------------------------------- ### Push Feature Branch Source: https://github.com/sgamrekelashvili/expo-audio-studio/blob/main/CONTRIBUTING.md Push your feature branch to the origin remote. ```bash git push origin feature/your-feature-name ``` -------------------------------- ### Event Listeners API Source: https://github.com/sgamrekelashvili/expo-audio-studio/blob/main/README.md APIs for subscribing to various audio-related events. ```APIDOC ## addListener ### Description Subscribes to specific audio events to receive real-time updates. ### Method `addListener(eventName, callback)` ### Parameters #### Path Parameters - **eventName** (string) - Required - The name of the event to listen for. Supported events include: - `'onRecorderStatusChange'` - `'onRecorderAmplitude'` - `'onAudioChunk'` - `'onVoiceActivityDetected'` - `'onPlayerStatusChange'` - **callback** (function) - Required - The function to be called when the event is triggered. The event data structure depends on the `eventName`. ### Event Data Structures #### `onRecorderStatusChange` - **status** (string) - The current status of the recorder ('recording', 'stopped', 'paused', 'resumed', 'error'). #### `onRecorderAmplitude` - **amplitude** (number) - The current amplitude level in dB. #### `onAudioChunk` - **base64** (string) - Base64 encoded PCM audio data (Int16 samples, 16kHz sample rate, mono channel). #### `onVoiceActivityDetected` - **isVoiceDetected** (boolean) - Indicates if voice activity is detected. - **confidence** (number) - Confidence level of the voice detection (0.0-1.0). - **timestamp** (number) - Timestamp of the event. - **isStateChange** (boolean) - True if the voice activity state has changed. - **previousState** (boolean) - The previous voice activity state. - **eventType** (string) - Type of voice activity event ('speech_start', 'speech_continue', 'silence_start', 'silence_continue'). #### `onPlayerStatusChange` - **isPlaying** (boolean) - Indicates if the player is currently playing. - **didJustFinish** (boolean) - Indicates if the playback just finished. ``` -------------------------------- ### Listen to Audio Chunks Source: https://github.com/sgamrekelashvili/expo-audio-studio/blob/main/README.md Listen for audio chunks, which are Base64 encoded PCM audio data. This requires `setListenToChunks(true)` to be called first. The data is in Int16 format at a 16kHz sample rate and mono channel. ```typescript import ExpoAudioStudio from 'expo-audio-studio'; // Listen to audio chunks (requires setListenToChunks(true)) const chunkSubscription = ExpoAudioStudio.addListener( 'onAudioChunk', (event: AudioChunkEvent) => { // event.base64: string - Base64 encoded PCM audio data // Format: Int16 samples, 16kHz sample rate, mono channel } ); ```