### Development Setup for react-native-audio-analyzer Source: https://github.com/exzos28/react-native-audio-analyzer/blob/main/README.md Instructions for setting up the development environment for the react-native-audio-analyzer project. This includes cloning the repository, installing project dependencies with yarn, and running the example application to test functionalities. ```bash # Clone the repository git clone https://github.com/exzos28/react-native-audio-analyzer.git cd react-native-audio-analyzer # Install dependencies yarn install # Run the example app yarn example ``` -------------------------------- ### iOS Setup for react-native-audio-analyzer Source: https://github.com/exzos28/react-native-audio-analyzer/blob/main/README.md Steps to set up the library on iOS by navigating to the ios directory and installing CocoaPods dependencies. This ensures that the native components of the library are correctly linked for iOS applications. ```bash cd ios && pod install # or bundle exec pod install ``` -------------------------------- ### Install react-native-audio-analyzer and dependencies Source: https://github.com/exzos28/react-native-audio-analyzer/blob/main/README.md Instructions for installing the react-native-audio-analyzer library and its required dependency, react-native-nitro-modules, using npm or yarn. This setup is crucial for enabling the library's native module functionality. ```bash npm install react-native-audio-analyzer react-native-nitro-modules # or yarn add react-native-audio-analyzer react-native-nitro-modules ``` -------------------------------- ### Configure Project and Libraries (CMake) Source: https://github.com/exzos28/react-native-audio-analyzer/blob/main/android/CMakeLists.txt Configures the project name, C++ standard, and includes core source files, custom C++ sources, and the miniaudio library. It also sets up include directories and links necessary Android libraries. ```cmake cmake_minimum_required(VERSION 3.9.0) set(PACKAGE_NAME audioanalyzer) set(CMAKE_VERBOSE_MAKEFILE ON) set(CMAKE_CXX_STANDARD 20) # Miniaudio compilation flags add_definitions(-DMA_NO_PTHREAD_IN_HEADER=1) set(CACHE_DIR ${CMAKE_SOURCE_DIR}/build) file(GLOB_RECURSE CORE_SRC RELATIVE ${CMAKE_SOURCE_DIR} "./src/main/cpp/*.cpp") file(GLOB_RECURSE SOURCES RELATIVE ${CMAKE_SOURCE_DIR} "../cpp/*.cpp") # Add miniaudio source set(MINIAUDIO_SRC "../libs/miniaudio/miniaudio.c") add_library( ${PACKAGE_NAME} SHARED ${CORE_SRC} ${SOURCES} ${MINIAUDIO_SRC} ) # Add Nitrogen specs :) include(${CMAKE_SOURCE_DIR}/../nitrogen/generated/android/audioanalyzer+autolinking.cmake) # Set up local includes include_directories("src/main/cpp" "../cpp" "../libs/miniaudio") target_include_directories(${PACKAGE_NAME} PRIVATE "${CACHE_DIR}/download-cache") find_library(LOG_LIB log) find_library(OPENSLES_LIB OpenSLES) find_library(ANDROID_LIB android) # Link all libraries together target_link_libraries( ${PACKAGE_NAME} ${LOG_LIB} ${OPENSLES_LIB} ${ANDROID_LIB} ) ``` -------------------------------- ### Load Audio File from URL or Local Path (TypeScript) Source: https://context7.com/exzos28/react-native-audio-analyzer/llms.txt Downloads and caches an audio file from a remote URL or prepares a local file for processing. It returns the absolute path to the cached file, which can then be used with other library functions. Error handling is included for failed downloads or processing. ```typescript import { load } from 'react-native-audio-analyzer'; async function loadAudioFile() { try { // Load from remote URL const remoteUrl = 'https://file-examples.com/storage/fe180a8b03688f5559b9baf/2017/11/file_example_MP3_1MG.mp3'; const cachedPath = await load(remoteUrl); console.log('Cached file path:', cachedPath); // Returns: /data/user/0/audioanalyzer.example/cache/9349e0a758090499d982e320a10273ab.audio return cachedPath; } catch (error) { console.error('Failed to load audio file:', error); throw error; } } ``` -------------------------------- ### Load Audio File Source: https://context7.com/exzos28/react-native-audio-analyzer/llms.txt Downloads and caches an audio file from a remote URL or prepares a local file for processing. It returns the absolute path to the cached file. ```APIDOC ## POST /load ### Description Downloads and caches an audio file from a remote URL or prepares a local file for processing. This function handles network fetching, caching to the device's file system, and returns the absolute path to the cached file that can be used with other library functions. ### Method POST ### Endpoint /load ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **url** (string) - Required - The URL or local path of the audio file. ### Request Example ```json { "url": "https://file-examples.com/storage/fe180a8b03688f5559b9baf/2017/11/file_example_MP3_1MG.mp3" } ``` ### Response #### Success Response (200) - **cachedPath** (string) - The absolute path to the cached audio file. #### Response Example ```json { "cachedPath": "/data/user/0/audioanalyzer.example/cache/9349e0a758090499d982e320a10273ab.audio" } ``` ``` -------------------------------- ### Load and Cache Audio File Source: https://github.com/exzos28/react-native-audio-analyzer/blob/main/README.md Loads an audio file from a given URL and caches it on the device. It returns a Promise that resolves with the absolute file system path to the cached file, which can then be used for further analysis or processing by the library. ```typescript const path = load('https://file-examples.com/storage/fe180a8b03688f5559b9baf/2017/11/file_example_MP3_1MG.mp3', 500); // Returns: /data/user/0/audioanalyzer.example/cache/9349e0a758090499d982e320a10273ab.audio ``` -------------------------------- ### React Native Audio Waveform Visualization Source: https://context7.com/exzos28/react-native-audio-analyzer/llms.txt This React Native component visualizes audio waveforms by loading an audio file, computing its amplitude, and then applying various scaling and sampling techniques for different visualization styles. It handles loading states and potential errors during audio analysis. Dependencies include 'react-native-audio-analyzer'. ```typescript import { useCallback, useEffect, useState } from 'react'; import { ScrollView, StyleSheet, Text, View } from 'react-native'; import { load, computeAmplitude } from 'react-native-audio-analyzer'; import { robustScale, sample, scale, trimmedScale } from 'react-native-audio-analyzer/src/helpers'; export default function AudioWaveformVisualizer() { const [amplitudeData, setAmplitudeData] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const analyzeAudio = useCallback(async () => { try { setLoading(true); setError(null); // Load audio file from URL const audioUrl = 'https://file-examples.com/storage/fe180a8b03688f5559b9baf/2017/11/file_example_MP3_1MG.mp3'; const cachedPath = await load(audioUrl); console.log('Audio cached at:', cachedPath); // Compute 100 amplitude samples const amplitudes = computeAmplitude(cachedPath, 100); console.log('Extracted amplitudes:', amplitudes.length); setAmplitudeData(amplitudes); setLoading(false); } catch (err) { console.error('Audio analysis error:', err); setError(err instanceof Error ? err.message : 'Unknown error'); setLoading(false); } }, []); useEffect(() => { analyzeAudio(); }, [analyzeAudio]); if (loading) { return ( Loading audio... ); } if (error) { return ( Error: {error} ); } // Generate different visualizations const visualizations = [ { title: 'Original Amplitudes', data: amplitudeData, }, { title: 'Trimmed Scale (0-100%)', data: trimmedScale(amplitudeData, 0, 1), }, { title: 'Robust Scale (Outlier Resistant)', data: robustScale(amplitudeData, 0, 1), }, { title: 'Downsampled (35 bars)', data: scale(sample(amplitudeData, 35)), }, { title: 'Min-Max Normalized', data: scale(amplitudeData), }, ]; return ( {visualizations.map((viz, index) => ( {viz.title} {viz.data.map((amplitude, barIndex) => ( ))} ))} ); } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', backgroundColor: '#ffffff', }, visualization: { padding: 10, borderBottomWidth: 1, borderBottomColor: '#e0e0e0', }, title: { fontSize: 14, fontWeight: 'bold', marginBottom: 8, }, waveformScroll: { maxHeight: 120, }, waveformContainer: { flexDirection: 'row', alignItems: 'center', paddingVertical: 10, }, waveformBar: { width: 3, backgroundColor: '#2196F3', marginHorizontal: 2, minHeight: 2, }, }); ``` -------------------------------- ### Normalize Amplitude Data with Robust Scaling (IQR) Source: https://context7.com/exzos28/react-native-audio-analyzer/llms.txt The `robustScale` function normalizes amplitude data using the Interquartile Range (IQR), making it resistant to outliers. It uses percentiles (default 5th and 75th) to set scaling bounds, ideal for audio with volume spikes. The function takes the amplitude array and optional custom percentile bounds as input, returning the robustly scaled array. ```typescript import { computeAmplitude, load } from 'react-native-audio-analyzer'; import { robustScale } from 'react-native-audio-analyzer/src/helpers'; async function robustNormalization() { const filePath = await load('https://example.com/audio-with-noise.mp3'); const amplitudes = computeAmplitude(filePath, 100); // Apply robust scaling with default percentiles (0.05, 0.75) const robustScaled = robustScale(amplitudes); console.log('Robust scaled:', robustScaled); // Custom percentiles for more aggressive outlier filtering const customScaled = robustScale(amplitudes, 0.1, 0.9); console.log('Custom percentiles:', customScaled); // Values are clamped to [0, 1] range const allInRange = customScaled.every(v => v >= 0 && v <= 1); console.log('All values in range:', allInRange); // true return robustScaled; } ``` -------------------------------- ### Resample Amplitude Array with Uniform Sampling Source: https://context7.com/exzos28/react-native-audio-analyzer/llms.txt The `sample` function resamples an array of amplitudes to a new size by uniformly selecting values. It's useful for reducing data points for visualization or adjusting waveform resolution without re-processing the audio. It takes the amplitude array and the desired new size as input and returns the resampled array. ```typescript import { computeAmplitude, load } from 'react-native-audio-analyzer'; import { sample, scale } from 'react-native-audio-analyzer/src/helpers'; async function resampleAudio() { const filePath = await load('https://example.com/audio.mp3'); // Get high-resolution amplitude data const highResAmplitudes = computeAmplitude(filePath, 1000); console.log('High-res samples:', highResAmplitudes.length); // 1000 // Downsample to 50 samples for a simplified waveform const lowResAmplitudes = sample(highResAmplitudes, 50); console.log('Low-res samples:', lowResAmplitudes.length); // 50 // Combine with scale for normalized, downsampled data const finalData = scale(sample(highResAmplitudes, 35)); console.log('Final samples:', finalData.length); // 35 return finalData; } ``` -------------------------------- ### Compute Amplitude Data from Audio File (TypeScript) Source: https://context7.com/exzos28/react-native-audio-analyzer/llms.txt Analyzes an audio file and extracts amplitude data as an array of normalized values between 0 and 1. This function processes the entire audio track and returns a specified number of samples distributed evenly across the audio duration. The output array is suitable for direct use in visualizations. It requires a file path obtained from the `load` function and the desired number of samples. ```typescript import { load, computeAmplitude } from 'react-native-audio-analyzer'; async function analyzeAudio() { try { // First load the audio file const filePath = await load('https://example.com/audio.mp3'); // Compute amplitude data with 500 samples const amplitudes = computeAmplitude(filePath, 500); console.log('Number of samples:', amplitudes.length); // 500 console.log('First amplitude:', amplitudes[0]); // 0.0 to 1.0 console.log('Amplitude range:', Math.min(...amplitudes), 'to', Math.max(...amplitudes)); // Use amplitudes for visualization return amplitudes; } catch (error) { console.error('Audio analysis failed:', error); throw error; } } ``` -------------------------------- ### Compute Audio Amplitude Data Source: https://github.com/exzos28/react-native-audio-analyzer/blob/main/README.md Analyzes an audio file to extract amplitude values. It takes the file path and the desired number of samples as input, returning an array of numbers representing amplitude levels between 0 and 1. This is fundamental for audio visualization. ```typescript import { computeAmplitude } from 'react-native-audio-analyzer'; // Analyze audio file and get amplitude data const amplitudeData = computeAmplitude('/path/to/audio.mp3', 1000); console.log('Amplitude data:', amplitudeData); ``` -------------------------------- ### Normalize Amplitude Array using Min-Max Scaling (TypeScript) Source: https://context7.com/exzos28/react-native-audio-analyzer/llms.txt Normalizes an array of amplitude values to a 0-1 range using min-max scaling. This helper function identifies the minimum and maximum values in the input array and linearly scales all values to fit within the 0-1 range. This ensures consistent visualization regardless of the original audio's dynamic range. It takes an array of numbers as input and returns a new array with scaled values. ```typescript import { computeAmplitude, load } from 'react-native-audio-analyzer'; import { scale } from 'react-native-audio-analyzer/src/helpers'; async function normalizeAmplitudes() { const filePath = await load('https://example.com/audio.mp3'); const rawAmplitudes = computeAmplitude(filePath, 100); console.log('Raw amplitudes:', rawAmplitudes); // [0.05, 0.15, 0.25, 0.35, 0.45, ...] const scaledAmplitudes = scale(rawAmplitudes); console.log('Scaled amplitudes:', scaledAmplitudes); // [0.0, 0.25, 0.5, 0.75, 1.0, ...] // Now the minimum amplitude is 0 and maximum is 1 console.log('Min:', Math.min(...scaledAmplitudes)); // 0 console.log('Max:', Math.max(...scaledAmplitudes)); // 1 return scaledAmplitudes; } ``` -------------------------------- ### Scale Amplitude Array Source: https://context7.com/exzos28/react-native-audio-analyzer/llms.txt Normalizes an array of amplitude values to a 0-1 range using min-max scaling. This helper function finds the minimum and maximum values and linearly scales all values to fit within the 0-1 range. ```APIDOC ## POST /scale ### Description Normalizes an array of amplitude values to a 0-1 range using min-max scaling. This helper function finds the minimum and maximum values in the input array and linearly scales all values to fit within the 0-1 range, making amplitudes suitable for consistent visualization regardless of the original audio's dynamic range. ### Method POST ### Endpoint /scale ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **arr** (number[]) - Required - An array of amplitude values. ### Request Example ```json { "arr": [ 0.05, 0.15, 0.25, 0.35, 0.45 ] } ``` ### Response #### Success Response (200) - **scaledAmplitudes** (number[]) - An array of amplitude values scaled to the 0-1 range. #### Response Example ```json { "scaledAmplitudes": [ 0.0, 0.25, 0.5, 0.75, 1.0 ] } ``` ``` -------------------------------- ### Normalize Amplitude Data by Trimming Extremes Source: https://context7.com/exzos28/react-native-audio-analyzer/llms.txt The `trimmedScale` function normalizes amplitude data by first trimming extreme values based on specified percentiles (default 3rd and 95th) and then scaling the remaining range to 0-1. This is effective for cleaning visualizations of audio with inconsistent volume levels. It accepts the amplitude array and optional lower/upper percentile bounds, returning the trimmed and scaled array. ```typescript import { computeAmplitude, load } from 'react-native-audio-analyzer'; import { trimmedScale } from 'react-native-audio-analyzer/src/helpers'; async function trimmedNormalization() { const filePath = await load('https://example.com/variable-volume.mp3'); const amplitudes = computeAmplitude(filePath, 100); // Apply trimmed scaling with default percentiles (0.03, 0.95) const trimmedData = trimmedScale(amplitudes); console.log('Trimmed scaled data:', trimmedData); // Full range trimming (no outlier removal) const fullRangeTrimmed = trimmedScale(amplitudes, 0, 1); console.log('Full range:', fullRangeTrimmed); // Aggressive trimming (remove more extremes) const aggressiveTrimmed = trimmedScale(amplitudes, 0.1, 0.85); console.log('Aggressive trimming:', aggressiveTrimmed); return trimmedData; } ``` -------------------------------- ### Compute Amplitude Source: https://context7.com/exzos28/react-native-audio-analyzer/llms.txt Analyzes an audio file and extracts amplitude data as an array of normalized values between 0 and 1. It returns the specified number of amplitude samples, distributed evenly across the audio duration. ```APIDOC ## POST /computeAmplitude ### Description Analyzes an audio file and extracts amplitude data as an array of normalized values between 0 and 1. This native function processes the entire audio track and returns the specified number of amplitude samples, distributing them evenly across the audio duration. The returned array can be directly used for visualization purposes. ### Method POST ### Endpoint /computeAmplitude ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **filePath** (string) - Required - The absolute path to the audio file (obtained from the `load` function). - **outputSampleCount** (number) - Required - The desired number of amplitude samples to compute. ### Request Example ```json { "filePath": "/data/user/0/audioanalyzer.example/cache/9349e0a758090499d982e320a10273ab.audio", "outputSampleCount": 500 } ``` ### Response #### Success Response (200) - **amplitudes** (number[]) - An array of normalized amplitude values (0.0 to 1.0). #### Response Example ```json { "amplitudes": [ 0.1, 0.2, 0.3, 0.4, 0.5, // ... more samples 0.9 ] } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.