### Audio Visualization Setup Source: https://github.com/birdofpreyru/react-native-audio/blob/master/_autodocs/_COMPLETION_REPORT.txt This example shows the basic setup for audio visualization. It involves starting the recorder and listening for recording events to process audio data for visualization. ```typescript import AudioRecorderPlayer from 'react-native-audio-recorder-player'; const audioRecorderPlayer = new AudioRecorderPlayer(); const startVisualization = async () => { try { const path = await audioRecorderPlayer.startRecorder(); audioRecorderPlayer.addRecordBackListener((e) => { // Process e.current_position and potentially audio data chunks // for visualization purposes. console.log('Recording for visualization:', e); }); console.log('Visualization started, recording path:', path); } catch (error) { console.error('Error starting visualization:', error); } }; ``` -------------------------------- ### Complete Audio Initialization Example (TypeScript) Source: https://github.com/birdofpreyru/react-native-audio/blob/master/_autodocs/api-reference/functions.md A comprehensive example demonstrating the full initialization process, including checking input availability, configuring the system, setting up input streams and players, and starting recording. ```typescript import { configAudioSystem, getInputAvailable, InputAudioStream, SamplePlayer, AUDIO_FORMATS, AUDIO_SOURCES, CHANNEL_CONFIGS, } from "@dr.pogodin/react-native-audio"; async function initializeCompleteAudioSetup() { // 1. Check if input is available const hasInput = await getInputAvailable(); if (!hasInput) { throw new Error("No audio input available"); } // 2. Configure audio system await configAudioSystem(); // 3. Create and setup input stream const stream = new InputAudioStream( AUDIO_SOURCES.RAW, 44100, CHANNEL_CONFIGS.MONO, AUDIO_FORMATS.PCM_16BIT, 4096, ); stream.addErrorListener((error) => { console.error("Stream error:", error); }); stream.addChunkListener((chunk, chunkId) => { console.log(`Received chunk ${chunkId}`); }); // 4. Create and setup player const player = new SamplePlayer(); player.addErrorListener((error) => { console.error("Player error:", error); }); // 5. Start recording const started = await stream.start(); if (!started) { throw new Error("Failed to start stream"); } return { stream, player }; } ``` -------------------------------- ### Complete Initialization Example Source: https://github.com/birdofpreyru/react-native-audio/blob/master/_autodocs/_COMPLETION_REPORT.txt Provides a comprehensive example of initializing the audio library, including setting up configuration options and preparing for recording or playback. ```typescript import AudioRecorderPlayer, { AudioSetOptions } from 'react-native-audio-recorder-player'; const initializeAudio = async () => { const audioRecorderPlayer = new AudioRecorderPlayer(); const audioSetOptions: AudioSetOptions = { // Example options, adjust as needed numberOfChannels: 1, sampleRate: 44100, bitRate: 128000, encoding: 'aac', wavFile: 'sample.wav' // Optional: specify a default WAV file name }; try { const result = await audioRecorderPlayer.setAudioSet(audioSetOptions); console.log('Audio set options applied:', result); // Now the library is configured and ready for operations return audioRecorderPlayer; } catch (error) { console.error('Error initializing audio:', error); return null; } }; // To use: // initializeAudio().then(player => { // if (player) { // // Proceed with recording or playback // } // }); ``` -------------------------------- ### Install react-native-audio and peer dependencies Source: https://github.com/birdofpreyru/react-native-audio/blob/master/README.md Use this command to install the library and its required peer dependencies. Ensure you have followed the react-native-permissions setup for audio recording permissions. ```sh npx install-peerdeps @dr.pogodin/react-native-audio ``` -------------------------------- ### Complete Audio Initialization and Usage Example Source: https://github.com/birdofpreyru/react-native-audio/blob/master/_autodocs/api-reference/exports.md An example demonstrating how to initialize the audio system, set up an InputAudioStream for recording, and use a SamplePlayer for playback. Includes error handling and platform-specific path adjustments for Catalyst. ```typescript import { InputAudioStream, SamplePlayer, AUDIO_FORMATS, AUDIO_SOURCES, CHANNEL_CONFIGS, configAudioSystem, getInputAvailable, IS_MAC_CATALYST, } from "@dr.pogodin/react-native-audio"; async function initializeAudio() { // Check for input availability const hasInput = await getInputAvailable(); if (!hasInput) { console.error("No audio input available"); return; } // Configure audio system await configAudioSystem(); // Create stream const stream = new InputAudioStream( AUDIO_SOURCES.RAW, 44100, CHANNEL_CONFIGS.MONO, AUDIO_FORMATS.PCM_16BIT, 4096, ); // Setup error handling stream.addErrorListener((error) => { console.error("Stream error:", error); }); // Setup data processing stream.addChunkListener((chunk, chunkId) => { console.log(`Received chunk ${chunkId}: ${chunk.length} bytes`); }); // Start recording const started = await stream.start(); console.log("Recording:", started ? "started" : "failed"); // Create player const player = new SamplePlayer(); player.addErrorListener((error) => { console.error("Player error:", error); }); // Load and play sample if (IS_MAC_CATALYST) { const path = `${MainBundlePath}/Contents/Resources/assets/sample.mp3`; await player.load("sample", path); } else { const path = `${MainBundlePath}/sample.mp3`; await player.load("sample", path); } await player.play("sample", false); // Cleanup return () => { stream.destroy(); player.destroy(); }; } ``` -------------------------------- ### .start() Source: https://github.com/birdofpreyru/react-native-audio/blob/master/README.md Starts the audio stream recording, initializing the stream on the native side. May request audio recording permission. Resolves to true if started successfully, false otherwise. ```APIDOC ## .start() ### Description Starts the audio stream recording. This method actually initializes the stream on the native side, and starts the recording. **Note:** If necessary, this method will ask app user for the audio recoding permission, using the [react-native-permissions] library. ### Method ```ts stream.start(): Promise; ``` ### Response #### Success Response (200) - **boolean** - _true_ if the stream has started successfully and is [.active], _false_ otherwise. ``` -------------------------------- ### Robust Audio Setup with Retries Source: https://github.com/birdofpreyru/react-native-audio/blob/master/_autodocs/errors.md Implements an audio setup function that retries initialization up to three times with a one-second delay between attempts. It throws an error if setup fails after all retries. ```typescript async function robustAudioSetup() { let retries = 3; while (retries > 0) { try { const stream = new InputAudioStream( AUDIO_SOURCES.RAW, 44100, CHANNEL_CONFIGS.MONO, AUDIO_FORMATS.PCM_16BIT, 4096, ); stream.addErrorListener((error) => { console.error("Stream error:", error); // Restart on error this.restart(); }); const started = await stream.start(); if (started) return stream; } catch (error) { console.error(`Setup attempt ${4 - retries} failed:`, error); retries--; if (retries > 0) { // Wait before retrying await new Promise(resolve => setTimeout(resolve, 1000)); } } } throw new Error("Failed to setup audio after 3 attempts"); } ``` -------------------------------- ### Create and Start InputAudioStream Source: https://github.com/birdofpreyru/react-native-audio/blob/master/README.md Demonstrates how to create and configure an InputAudioStream, add listeners for errors and data chunks, and start the audio capture. Ensure to call stream.destroy() to release resources. ```javascript import { AUDIO_FORMATS, AUDIO_SOURCES, CHANNEL_CONFIGS, InputAudioStream, } from "@dr.pogodin/react-native-audio"; function createAndStartAudioStream() { const stream = new InputAudioStream( AUDIO_SOURCES.RAW, 44100, // Sample rate in Hz. CHANNEL_CONFIGS.MONO, AUDIO_FORMATS.PCM_16BIT, 4096, // Sampling size. ); stream.addErrorListener((error) => { // Do something with a stream error. }); stream.addChunkListener((chunk, chunkId) => { // Pause the stream for the chunk processing. The point is: if your chunk // processing in this function is too slow, and chunks arrive faster than // this callback is able to handle them, it will rapidly crash the app, // with out of memory error. Muting the stream ignores any new chunks // until stream.unmute() is called, thus protecting from the crash. // And if your chunk processing is rapid enough, not chunks won't be // skipped. The "chunkId" argument is just sequential chunk numbers, // by which you may judge whether any chunks have been skipped between // this callback calls or not. stream.mute(); // Do something with the chunk. // Resumes the stream. stream.unmute(); }); stream.start(); // Call stream.destroy() to stop the stream and release any associated // resources. If you need to temporarily stop and then resume the stream, // use .mute() and .unmute() methods instead. } ``` -------------------------------- ### Start Basic Audio Recording Source: https://github.com/birdofpreyru/react-native-audio/blob/master/_autodocs/README.md Configures the audio system and starts a raw audio input stream. Handles errors and processes audio chunks in real-time. ```typescript import { InputAudioStream, AUDIO_FORMATS, AUDIO_SOURCES, CHANNEL_CONFIGS, configAudioSystem, } from "@dr.pogodin/react-native-audio"; async function startRecording() { // Configure audio system await configAudioSystem(); // Create stream const stream = new InputAudioStream( AUDIO_SOURCES.RAW, 44100, CHANNEL_CONFIGS.MONO, AUDIO_FORMATS.PCM_16BIT, 4096, ); // Handle errors stream.addErrorListener((error) => { console.error("Recording error:", error); }); // Process audio stream.addChunkListener((chunk, chunkId) => { console.log(`Chunk ${chunkId}: ${chunk.length} bytes`); }); // Start const success = await stream.start(); return success ? stream : null; } ``` -------------------------------- ### Setup Error Listeners First Source: https://github.com/birdofpreyru/react-native-audio/blob/master/_autodocs/README.md Register error listeners on an audio stream before starting it. This ensures that any errors occurring during initialization or startup are captured and handled. ```typescript const stream = new InputAudioStream(/* ... */); stream.addErrorListener((error) => { // Handle error before starting }); await stream.start(); ``` -------------------------------- ### Install React Native Audio Source: https://github.com/birdofpreyru/react-native-audio/blob/master/_autodocs/README.md Installs the library and its peer dependencies. Ensure you have react, react-native, and react-native-permissions (>=3.8) installed. ```bash npx install-peerdeps @dr.pogodin/react-native-audio ``` -------------------------------- ### .start() Source: https://github.com/birdofpreyru/react-native-audio/blob/master/_autodocs/api-reference/InputAudioStream.md Starts the audio stream recording. Initializes the stream on the native side and begins recording. It may request audio recording permission if necessary. ```APIDOC ## .start() ### Description Starts the audio stream recording. This method initializes the stream on the native side and begins recording. If necessary, it requests audio recording permission from the user via the `react-native-permissions` library. ### Returns A promise that resolves to `true` if the stream started successfully and is active, or `false` otherwise. ### Example ```typescript const isActive = await stream.start(); if (isActive) { console.log("Stream started successfully"); } else { console.log("Failed to start stream"); } ``` ``` -------------------------------- ### Start Metro Bundler Source: https://github.com/birdofpreyru/react-native-audio/blob/master/example/README.md Run this command from the root of your React Native project to start the Metro dev server. This is essential for the development workflow. ```sh # Using npm npm start # OR using Yarn yarn start ``` -------------------------------- ### Voice Communication with Effects Source: https://github.com/birdofpreyru/react-native-audio/blob/master/_autodocs/_COMPLETION_REPORT.txt This example outlines the setup for voice communication, potentially involving real-time audio processing and effects. The specific effects implementation would depend on additional libraries or native modules. ```typescript import AudioRecorderPlayer from 'react-native-audio-recorder-player'; const audioRecorderPlayer = new AudioRecorderPlayer(); // For voice communication, you would typically start recording // and stream the audio data to a remote peer or service. // Applying effects would happen either on the sender's side before streaming // or on the receiver's side after receiving. const startVoiceCommunication = async () => { try { const path = await audioRecorderPlayer.startRecorder(); // ... logic to stream audio data and apply effects ... console.log('Voice communication started, recording path:', path); } catch (error) { console.error('Error starting voice communication:', error); } }; ``` -------------------------------- ### Start Audio Stream Recording Source: https://github.com/birdofpreyru/react-native-audio/blob/master/README.md Initializes and starts the audio stream recording. May request user permission. Resolves to true if the stream is active, false otherwise. ```typescript stream.start(): Promise; ``` -------------------------------- ### Start Audio Stream Source: https://github.com/birdofpreyru/react-native-audio/blob/master/_autodocs/api-reference/InputAudioStream.md Initializes the stream on the native side and begins recording. It may request audio recording permission. Returns a promise that resolves to true if the stream started successfully and is active, or false otherwise. ```typescript const isActive = await stream.start(); if (isActive) { console.log("Stream started successfully"); } else { console.log("Failed to start stream"); } ``` -------------------------------- ### Install CocoaPods Dependencies Source: https://github.com/birdofpreyru/react-native-audio/blob/master/example/README.md Before running the iOS app, install CocoaPods dependencies. Run 'bundle install' once to install the bundler, and 'bundle exec pod install' after updating native dependencies. ```sh bundle install bundle exec pod install ``` -------------------------------- ### Setting up and using InputAudioStream Source: https://github.com/birdofpreyru/react-native-audio/blob/master/_autodocs/api-reference/InputAudioStream.md Demonstrates how to initialize an InputAudioStream, add error and data listeners, start recording, and clean up the stream. Ensure to handle potential buffer overflows by muting the stream before processing chunks. ```typescript import { AUDIO_FORMATS, AUDIO_SOURCES, CHANNEL_CONFIGS, InputAudioStream, } from "@dr.pogodin/react-native-audio"; function setupAudioStream() { const stream = new InputAudioStream( AUDIO_SOURCES.RAW, 44100, CHANNEL_CONFIGS.MONO, AUDIO_FORMATS.PCM_16BIT, 4096, ); // Add error handler stream.addErrorListener((error) => { console.error("Audio error:", error.message); }); // Add data handler stream.addChunkListener((chunk, chunkId) => { // Protect against buffer overflow stream.mute(); // Process audio chunk const audioData = new Int16Array(chunk.buffer); console.log(`Chunk ${chunkId}: ${audioData.length} samples`); stream.unmute(); }); // Start recording stream.start().then((success) => { if (success) { console.log("Recording started"); } }); // Later, cleanup return () => { stream.destroy(); }; } ``` -------------------------------- ### InputAudioStream with AUDIO_FORMATS Source: https://github.com/birdofpreyru/react-native-audio/blob/master/_autodocs/types.md Example of initializing an InputAudioStream using different AUDIO_FORMATS. Use PCM_16BIT for recommended quality or PCM_8BIT for a lower quality/size tradeoff. ```typescript import { AUDIO_FORMATS, InputAudioStream } from "@dr.pogodin/react-native-audio"; // Use 16-bit PCM, the recommended format const stream = new InputAudioStream( AUDIO_SOURCES.RAW, 44100, CHANNEL_CONFIGS.MONO, AUDIO_FORMATS.PCM_16BIT, // Recommended 4096, ); // Or use 8-bit for lower quality/size tradeoff const lowQualityStream = new InputAudioStream( AUDIO_SOURCES.RAW, 44100, CHANNEL_CONFIGS.MONO, AUDIO_FORMATS.PCM_8BIT, 4096, ); ``` -------------------------------- ### Live Audio Visualization Stream Source: https://github.com/birdofpreyru/react-native-audio/blob/master/_autodocs/README.md This example demonstrates setting up an audio stream for live visualization. It configures a raw audio stream and uses a chunk listener to perform FFT analysis on incoming audio data, updating the visualization. The stream is muted during processing to avoid issues. ```typescript const stream = new InputAudioStream( AUDIO_SOURCES.RAW, 44100, CHANNEL_CONFIGS.MONO, AUDIO_FORMATS.PCM_16BIT, 4096, ); stream.addChunkListener((chunk, chunkId) => { stream.mute(); // Pause during processing const audioData = new Int16Array(chunk.buffer); const fft = performFFT(audioData); updateVisualization(fft); stream.unmute(); // Resume }); await stream.start(); ``` -------------------------------- ### Basic Audio Recording in React Native Source: https://github.com/birdofpreyru/react-native-audio/blob/master/_autodocs/_COMPLETION_REPORT.txt Demonstrates the fundamental setup and usage for recording audio. Ensure necessary permissions are handled before initiating recording. ```typescript import AudioRecorderPlayer from 'react-native-audio-recorder-player'; const audioRecorderPlayer = new AudioRecorderPlayer(); const startRecording = async () => { try { const path = await audioRecorderPlayer.startRecorder(); audioRecorderPlayer.addRecordBackListener((e) => { // Handle recording progress return; }); console.log('Recording started:', path); } catch (error) { console.error('Error starting recording:', error); } }; const stopRecording = async () => { try { const result = await audioRecorderPlayer.stopRecorder(); audioRecorderPlayer.removeRecordBackListener(); console.log('Recording stopped:', result); } catch (error) { console.error('Error stopping recording:', error); } }; ``` -------------------------------- ### React Native Audio Component Usage Source: https://github.com/birdofpreyru/react-native-audio/blob/master/_autodocs/EXPORTS.md Example of using the React Native Audio library within a React component. Demonstrates setting up an audio stream, handling errors, and playing samples. Ensure all peer dependencies are installed. ```typescript import React, { useEffect, useRef, useState } from 'react'; import { View, Button, Text } from 'react-native'; import { InputAudioStream, SamplePlayer, AUDIO_FORMATS, AUDIO_SOURCES, CHANNEL_CONFIGS, configAudioSystem, getInputAvailable, } from "@dr.pogodin/react-native-audio"; export default function AudioApp() { const { current: refs } = useRef({ stream: null as InputAudioStream | null, player: null as SamplePlayer | null, }); useEffect(() => { (async () => { // Configure and check availability await configAudioSystem(); const available = await getInputAvailable(); if (available) { // Create stream refs.stream = new InputAudioStream( AUDIO_SOURCES.RAW, 44100, CHANNEL_CONFIGS.MONO, AUDIO_FORMATS.PCM_16BIT, 4096, ); // Add listeners refs.stream.addErrorListener((error) => { console.error("Stream error:", error); }); refs.stream.addChunkListener((chunk, chunkId) => { console.log(`Chunk ${chunkId}: ${chunk.length} bytes`); }); // Start recording await refs.stream.start(); } // Create player refs.player = new SamplePlayer(); refs.player.addErrorListener((error) => { console.error("Player error:", error); }); })(); return () => { refs.stream?.destroy(); refs.player?.destroy(); }; }, [refs]); return ( Audio application