### Install iOS Pods
Source: https://docs.swmansion.com/react-native-audio-api/docs/fundamentals/getting-started
Installs the necessary CocoaPods for iOS development after adding native dependencies. This command should be run from the 'ios' directory.
```bash
cd ios && pod install && cd ..
```
--------------------------------
### Install react-native-audio-api Package
Source: https://docs.swmansion.com/react-native-audio-api/docs/fundamentals/getting-started
Installs the react-native-audio-api package using different package managers. This is the first step to integrate the audio functionality into your React Native project.
```bash
npx expo install react-native-audio-api
```
```bash
npm install react-native-audio-api
```
```bash
yarn add react-native-audio-api
```
--------------------------------
### Play Audio Buffer in React Native
Source: https://docs.swmansion.com/react-native-audio-api/docs/guides/lets-make-some-noise
This snippet illustrates the complete process of playing an audio file: initializing AudioContext, decoding audio data, creating an AudioBufferSourceNode, connecting it to the audio context's destination, and starting playback for a specified duration.
```javascript
import React from 'react';
import { View, Button } from 'react-native';
import { AudioContext } from 'react-native-audio-api';
export default function App() {
const handlePlay = async () => {
const audioContext = new AudioContext();
const audioBuffer = await fetch('https://software-mansion.github.io/react-native-audio-api/audio/music/example-music-01.mp3')
.then((response) => response.arrayBuffer())
.then((arrayBuffer) => audioContext.decodeAudioData(arrayBuffer));
const playerNode = audioContext.createBufferSource();
playerNode.buffer = audioBuffer;
playerNode.connect(audioContext.destination);
playerNode.start(audioContext.currentTime);
playerNode.stop(audioContext.currentTime + 10);
};
return (
);
}
```
--------------------------------
### Run Expo Development Builds
Source: https://docs.swmansion.com/react-native-audio-api/docs/fundamentals/getting-started
Commands to run iOS and Android development builds for Expo projects. These are necessary because react-native-audio-api is not included in the Expo Go app.
```bash
npx expo run:ios
```
```bash
npx expo run:android
```
--------------------------------
### Example Usage of Custom Audio Node
Source: https://docs.swmansion.com/react-native-audio-api/docs/guides/create-your-own-effect
This example demonstrates how to use the custom `MyProcessorNode` within a React Native component. It initializes an `AudioContext`, creates an `OscillatorNode` and the custom `MyProcessorNode`, connects them, and starts the audio playback.
```typescript
import {
AudioContext,
OscillatorNode,
} from 'react-native-audio-api';
import { MyProcessorNode } from './types';
function App() {
const audioContext = new AudioContext();
const oscillator = audioContext.createOscillator();
// constructor is put in global scope
const processor = new MyProcessorNode(audioContext, global.createCustomProcessorNode(audioContext.context));
oscillator.connect(processor);
processor.connect(audioContext.destination);
oscillator.start(audioContext.currentTime);
}
```
--------------------------------
### AudioBufferSourceNode Methods: start()
Source: https://docs.swmansion.com/react-native-audio-api/docs/sources/audio-buffer-source-node
Details the `start` method for scheduling and initiating playback of the audio buffer.
```APIDOC
## AudioBufferSourceNode Methods: start()
### Description
Schedules the `AudioBufferSourceNode` to begin playback of its associated `AudioBuffer`. Playback can be immediate or scheduled for a future time, with options to specify the start offset and duration.
### Method
POST (Implicitly via `start` call)
### Endpoint
N/A (Method of `AudioBufferSourceNode`)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
- **when** (`number`, Optional) - The time in seconds when playback should start. If less than `AudioContext.currentTime` or 0, playback starts immediately. Defaults to 0.
- **offset** (`number`, Optional) - The position in seconds within the audio buffer to start playback. Defaults to 0.
- **duration** (`number`, Optional) - The playback duration in seconds. If omitted, playback continues until the buffer ends or `stop()` is called. Equivalent to `start(when, offset)` followed by `stop(when + duration)`.
### Request Example
```javascript
// Start immediately from the beginning
source.start();
// Start at 5 seconds into the buffer
source.start(0, 5);
// Start immediately, playing for 10 seconds from the beginning
source.start(0, 0, 10);
// Schedule to start 2 seconds from now, from the 3-second mark, for 5 seconds
source.start(audioContext.currentTime + 2, 3, 5);
```
### Response
#### Success Response (200)
`undefined`
#### Response Example
None
#### Errors:
- `RangeError`: `when`, `offset`, or `duration` is a negative number.
- `InvalidStateError`: If the node has already been started once.
```
--------------------------------
### AudioRecorder Start
Source: https://docs.swmansion.com/react-native-audio-api/docs/inputs/audio-recorder
Starts the audio stream from the system's audio input device.
```APIDOC
## start
### Description
Starts the stream from system audio input device.
### Method
start
### Request Example
```javascript
const result = audioRecorder.start();
if (result.status === 'success') {
const openedFilePath = result.path;
} else if (result.status === 'error') {
console.error(result.message);
}
```
```
--------------------------------
### Initialize and Use AudioBufferQueueSourceNode in React Native
Source: https://docs.swmansion.com/react-native-audio-api/docs/sources/audio-buffer-queue-source-node
Demonstrates how to initialize an AudioContext, create an AudioBufferQueueSourceNode, enqueue audio buffers, connect it to the audio destination, and start playback. This example assumes audio buffers are loaded elsewhere.
```javascript
import React, { useRef } from 'react';
import {
AudioContext,
AudioBufferQueueSourceNode,
} from 'react-native-audio-api';
function App() {
const audioContextRef = useRef(null);
if (!audioContextRef.current) {
audioContextRef.current = new AudioContext();
}
const audioBufferQueue = audioContextRef.current.createBufferQueueSource();
const buffer1 = ...; // Load your audio buffer here
const buffer2 = ...; // Load another audio buffer if needed
audioBufferQueue.enqueueBuffer(buffer1);
audioBufferQueue.enqueueBuffer(buffer2);
audioBufferQueue.connect(audioContextRef.current.destination);
audioBufferQueue.start(audioContextRef.current.currentTime);
}
```
--------------------------------
### AudioBufferSourceNode Initialization and Playback
Source: https://docs.swmansion.com/react-native-audio-api/docs/sources/audio-buffer-source-node
Demonstrates how to create an AudioBufferSourceNode, assign an AudioBuffer to it, connect it to the audio context destination, and start playback.
```APIDOC
## POST /websites/swmansion_react-native-audio-api
### Description
This section details the creation and playback of an `AudioBufferSourceNode` using the `react-native-audio-api`. It covers initializing the node, setting its buffer, connecting it to the audio destination, and initiating playback.
### Method
POST
### Endpoint
/websites/swmansion_react-native-audio-api
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
This endpoint does not directly accept a request body for initialization. Configuration is done programmatically.
### Request Example
```javascript
import { AudioContext } from 'react-native-audio-api';
async function playAudio(audioBuffer) {
const ctx = new AudioContext();
const source = await ctx.createBufferSource({ pitchCorrection: false });
source.buffer = audioBuffer;
source.playbackRate.value = 1.00;
source.detune.value = 0;
source.loop = false;
source.loopStart = 0.00;
source.loopEnd = 5.00;
source.connect(ctx.destination);
source.start();
}
```
### Response
#### Success Response (200)
This endpoint does not return a direct response body. Playback is initiated asynchronously.
#### Response Example
None
```
--------------------------------
### Clear Metro Bundler Cache
Source: https://docs.swmansion.com/react-native-audio-api/docs/fundamentals/getting-started
Commands to clear the Metro bundler cache when starting the development server. This can help resolve issues after installing or updating dependencies.
```bash
npx expo start -c
```
```bash
npm start -- --reset-cache
```
```bash
yarn start --reset-cache
```
--------------------------------
### AudioScheduledSourceNode - start method
Source: https://docs.swmansion.com/react-native-audio-api/docs/sources/audio-scheduled-source-node
Schedules the audio node to start playback at a specified time. If no time is provided, it starts immediately. This method can only be called once per node.
```APIDOC
## POST /audio/start
### Description
Schedules the node to start audio playback at a specified time. If no time is given, it starts immediately. This method can only be invoked once in the node's lifetime.
### Method
POST
### Endpoint
/audio/start
### Parameters
#### Query Parameters
- **when** (number) - Optional - The time, in seconds, at which the node will start to play.
### Request Example
```json
{
"when": 10.5
}
```
### Response
#### Success Response (200)
- **status** (string) - Indicates the operation was successful.
#### Response Example
```json
{
"status": "scheduled"
}
```
#### Errors:
- **RangeError**: `when` is a negative number.
- **InvalidStateError**: If the node has already been started once.
```
--------------------------------
### Initialize AudioContext in React Native
Source: https://docs.swmansion.com/react-native-audio-api/docs/guides/lets-make-some-noise
This snippet shows how to create an instance of AudioContext, which is the main object for controlling audio processing and node creation in the library. It's the first step towards playing any sound.
```javascript
import React from 'react';
import { View, Button } from 'react-native';
import { AudioContext } from 'react-native-audio-api';
export default function App() {
const handlePlay = async () => {
const audioContext = new AudioContext();
};
return (
);
}
```
--------------------------------
### Initialize and Play HLS Stream with StreamerNode
Source: https://docs.swmansion.com/react-native-audio-api/docs/sources/streamer-node
This example demonstrates how to create and use a StreamerNode to play an HLS stream. It initializes the AudioContext, creates a StreamerNode, sets the HLS source, connects it to the audio destination, and starts playback. Note that StreamerNode is mobile-only and can only be started once.
```javascript
import React, { useRef } from 'react';
import {
AudioContext,
StreamerNode,
} from 'react-native-audio-api';
function App() {
const audioContextRef = useRef(null);
if (!audioContextRef.current) {
audioContextRef.current = new AudioContext();
}
const streamer = audioContextRef.current.createStreamer();
streamer.initialize('link/to/your/hls/source');
streamer.connect(audioContextRef.current.destination);
streamer.start(audioContextRef.current.currentTime);
}
```
--------------------------------
### Record Audio to File with React Native Audio API
Source: https://docs.swmansion.com/react-native-audio-api/docs/inputs/audio-recorder
This snippet demonstrates how to enable and start recording audio directly to a file using the React Native Audio API. It includes setting up the audio session, requesting recording permissions, and handling the recording start and stop events. The output includes the path to the recorded file.
```javascript
import React, { useState } from 'react';
import { View, Pressable, Text } from 'react-native';
import { AudioRecorder, AudioManager } from 'react-native-audio-api';
AudioManager.setAudioSessionOptions({
iosCategory: 'record',
iosMode: 'default',
iosOptions: [],
});
const audioRecorder = new AudioRecorder();
// Enables recording to file with default configuration
audioRecorder.enableFileOutput();
const MyRecorder: React.FC = () => {
const [isRecording, setIsRecording] = useState(false);
const onStart = async () => {
if (isRecording) {
return;
}
// Make sure the permissions are granted
const permissions = await AudioManager.requestRecordingPermissions();
if (permissions !== 'Granted') {
console.warn('Permissions are not granted');
return;
}
// Activate audio session
const success = await AudioManager.setAudioSessionActivity(true);
if (!success) {
console.warn('Could not activate the audio session');
return;
}
const result = audioRecorder.start();
if (result.status === 'error') {
console.warn(result.message);
return;
}
console.log('Recording started to file:', result.path);
setIsRecording(true);
};
const onStop = () => {
if (!isRecording) {
return;
}
const result = audioRecorder.stop();
console.log(result);
setIsRecording(false);
AudioManager.setAudioSessionActivity(false);
};
return (
{isRecording ? 'Stop' : 'Record'}
);
};
export default MyRecorder;
```
--------------------------------
### RecorderAdapterNode Usage Example
Source: https://docs.swmansion.com/react-native-audio-api/docs/sources/recorder-adapter-node
Provides a practical code example demonstrating how to create and connect a RecorderAdapterNode with an AudioRecorder and an AudioContext.
```APIDOC
## GET /websites/swmansion_react-native-audio-api/RecorderAdapterNode/example
### Description
Demonstrates the usage of `RecorderAdapterNode` by creating an `AudioRecorder`, an `AudioContext`, and connecting them via the `RecorderAdapterNode`.
### Method
GET
### Endpoint
`/websites/swmansion_react-native-audio-api/RecorderAdapterNode/example`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```json
{
"example": "No request body needed for example"
}
```
### Response
#### Success Response (200)
- **codeSnippet** (string) - A string containing the JavaScript code example.
#### Response Example
```json
{
"codeSnippet": "const recorder = new AudioRecorder({\n sampleRate: 48000,\n bufferLengthInSamples: 48000,\n});\nconst audioContext = new AudioContext({ sampleRate: 48000 });\nconst recorderAdapterNode = aCtxRef.current.createRecorderAdapter();\n\nrecorder.connect(recorderAdapterNode);\nrecorderAdapterNode.connect(audioContext.destination)"
}
```
```
--------------------------------
### Configure Audio API Expo Plugin
Source: https://docs.swmansion.com/react-native-audio-api/docs/fundamentals/getting-started
Adds the react-native-audio-api Expo plugin to your app.json or app.config.js. This configuration allows for setting specific permissions and background modes for iOS and Android.
```json
{
"plugins": [
[
"react-native-audio-api",
{
"iosBackgroundMode": true,
"iosMicrophonePermission": "This app requires access to the microphone to record audio.",
"androidPermissions" : [
"android.permission.MODIFY_AUDIO_SETTINGS",
"android.permission.FOREGROUND_SERVICE",
"android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK"
],
"androidForegroundService": true,
"androidFSTypes": [
"mediaPlayback"
]
}
]
]
}
```
```javascript
export default {
...,
"plugins": [
[
"react-native-audio-api",
{
"iosBackgroundMode": true,
"iosMicrophonePermission": "This app requires access to the microphone to record audio.",
"androidPermissions" : [
"android.permission.MODIFY_AUDIO_SETTINGS",
"android.permission.FOREGROUND_SERVICE",
"android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK"
],
"androidForegroundService": true,
"androidFSTypes": [
"mediaPlayback"
]
}
]
]
};
```
--------------------------------
### Load and Decode Audio Data in React Native
Source: https://docs.swmansion.com/react-native-audio-api/docs/guides/lets-make-some-noise
This code demonstrates how to fetch an audio file from a remote URL and decode it into an AudioBuffer using the decodeAudioData method. This prepares the audio data for playback.
```javascript
import React from 'react';
import { View, Button } from 'react-native';
import { AudioContext } from 'react-native-audio-api';
export default function App() {
const handlePlay = async () => {
const audioContext = new AudioContext();
const audioBuffer = await fetch('https://software-mansion.github.io/react-native-audio-api/audio/music/example-music-01.mp3')
.then((response) => response.arrayBuffer())
.then((arrayBuffer) => audioContext.decodeAudioData(arrayBuffer));
};
return (
);
}
```
--------------------------------
### Create and Play AudioBufferSourceNode in React Native
Source: https://docs.swmansion.com/react-native-audio-api/docs/sources/audio-buffer-source-node
This snippet demonstrates how to create an AudioBufferSourceNode, assign an AudioBuffer to it, connect it to the audio context's destination, and start playback. It assumes an AudioContext and an AudioBuffer have already been initialized.
```javascript
import React, { useEffect, useRef, FC } from 'react';
import {
AudioContext,
AudioBufferSourceNode,
} from 'react-native-audio-api';
function App() {
const audioContextRef = useRef(null);
if (!audioContextRef.current) {
audioContextRef.current = new AudioContext();
}
const audioBufferSource = audioContextRef.current.createBufferSource();
const buffer = ...; // Load your audio buffer here
audioBufferSource.buffer = buffer;
audioBufferSource.connect(audioContextRef.current.destination);
audioBufferSource.start(audioContextRef.current.currentTime);
}
```
--------------------------------
### Start Audio Recording
Source: https://docs.swmansion.com/react-native-audio-api/docs/inputs/audio-recorder
Starts the audio stream from the system's audio input device. It returns a result object indicating success or failure, including the opened file path on success.
```javascript
const result = audioRecorder.start();
if (result.status === 'success') {
const openedFilePath = result.path;
} else if (result.status === 'error') {
console.error(result.message);
}
```
--------------------------------
### Configure and Control Audio with AudioManager in React Native
Source: https://docs.swmansion.com/react-native-audio-api/docs/system/audio-manager
This example demonstrates how to use the AudioManager from 'react-native-audio-api' to configure audio session options, set lock screen information, enable remote commands, observe audio interruptions, and subscribe to system events. It covers setting iOS-specific audio session categories and modes, displaying track information on the lock screen, and handling playback and pause commands.
```javascript
import { AudioManager } from 'react-native-audio-api';
import { useEffect } from 'react';
function App() {
// set AVAudioSession example options (iOS only)
AudioManager.setAudioSessionOptions({
iosCategory: 'playback',
iosMode: 'default',
iosOptions: ['defaultToSpeaker', 'allowBluetoothA2DP'],
});
// set info for track to be visible while device is locked
AudioManager.setLockScreenInfo({
title: 'Audio file',
artist: 'Software Mansion',
album: 'Audio API',
duration: 10,
});
useEffect(() => {
// enabling emission of events
AudioManager.enableRemoteCommand('remotePlay', true);
AudioManager.enableRemoteCommand('remotePause', true);
AudioManager.observeAudioInterruptions(true);
// callback to be invoked on 'remotePlay' event
const remotePlaySubscription = AudioManager.addSystemEventListener(
'remotePlay',
(event) => {
console.log('remotePlay event:', event);
}
);
// callback to be invoked on 'remotePause' event
const remotePauseSubscription = AudioManager.addSystemEventListener(
'remotePause',
(event) => {
console.log('remotePause event:', event);
}
);
// callback to be invoked on 'interruption' event
const interruptionSubscription = AudioManager.addSystemEventListener(
'interruption',
(event) => {
console.log('Interruption event:', event);
}
);
AudioManager.getDevicesInfo().then(console.log);
return () => {
remotePlaySubscription?.remove();
remotePauseSubscription?.remove();
interruptionSubscription?.remove();
};
}, []);
}
```
--------------------------------
### Initialize AudioContext for Recording in React Native
Source: https://docs.swmansion.com/react-native-audio-api/docs/inputs/audio-recorder
This snippet demonstrates the initialization of an `AudioContext` along with the `AudioRecorder` in React Native using the `react-native-audio-api` library. It configures the audio session for both playback and recording. This setup is a prerequisite for advanced audio processing and recording functionalities.
```javascript
import React, { useState } from 'react';
import { View, Pressable, Text } from 'react-native';
import {
AudioRecorder,
AudioContext,
AudioManager,
} from 'react-native-audio-api';
AudioManager.setAudioSessionOptions({
iosCategory: 'playAndRecord',
iosMode: 'default',
iosOptions: [],
});
const audioRecorder = new AudioRecorder();
const audioContext = new AudioContext();
const MyRecorder: React.FC = () => {
const [isRecording, setIsRecording] = useState(false);
const onStart = async () => {
if (isRecording) {
return;
}
// Make sure the permissions are granted
const permissions = await AudioManager.requestRecordingPermissions();
if (permissions !== 'Granted') {
console.warn('Permissions are not granted');
return;
}
// Activate audio session
const success = await AudioManager.setAudioSessionActivity(true);
if (!success) {
console.warn('Could not activate the audio session');
return;
}
// The rest of the recording logic would follow here...
```
--------------------------------
### Implement Key Press to Play Sound (React Native)
Source: https://docs.swmansion.com/react-native-audio-api/docs/guides/making-a-piano-keyboard
This function handles the logic for playing a sound when a key is pressed. It retrieves the audio context and buffer, creates a new `AudioBufferSourceNode`, connects it to the audio destination, starts playback, and stores the source node in `playingNotesRef` for later access.
```typescript
const onKeyPressIn = (which: KeyName) => {
const audioContext = audioContextRef.current!;
const buffer = bufferMapRef.current[which];
const source = new AudioBufferSourceNode(audioContext, {
buffer,
});
source.connect(audioContext.destination);
source.start();
playingNotesRef.current[which] = source;
};
```
--------------------------------
### Implement Attack Phase in onKeyPressIn Function
Source: https://docs.swmansion.com/react-native-audio-api/docs/guides/making-a-piano-keyboard
Handles the 'attack' phase of the audio envelope when a key is pressed. It creates an AudioBufferSourceNode and a GainNode, connects them, sets initial gain values, and starts the sound source. The note's state is stored in playingNotesRef.
```typescript
const onKeyPressIn = (which: KeyName) => {
const audioContext = audioContextRef.current!;
const buffer = bufferMapRef.current[which];
const tNow = audioContext.currentTime;
if (!audioContext || !buffer) {
return;
}
const source = audioContext.createBufferSource();
source.buffer = buffer;
const envelope = audioContext.createGain();
source.connect(envelope);
envelope.connect(audioContext.destination);
envelope.gain.setValueAtTime(0.001, tNow);
envelope.gain.exponentialRampToValueAtTime(1, tNow + 0.1);
source.start(tNow);
playingNotesRef.current[which] = { source, envelope, startedAt: tNow };
};
```
--------------------------------
### Create and Play Sine Wave Oscillator - JavaScript
Source: https://docs.swmansion.com/react-native-audio-api/docs/sources/oscillator-node
This snippet demonstrates how to create an OscillatorNode, configure it as a sine wave, set its frequency and gain, and then start the oscillator. It requires the AudioContext from 'react-native-audio-api'.
```javascript
import { AudioContext } from 'react-native-audio-api';
const ctx = new AudioContext();
const oscillator = ctx.createOscillator();
const gain = ctx.createGain();
oscillator.type = 'sine';
oscillator.frequency.value = 440;
oscillator.detune.value = 0;
gain.gain.value = 0.50;
oscillator.connect(gain);
gain.connect(ctx.destination);
oscillator.start();
```
--------------------------------
### Create and Use WorkletProcessingNode for Audio Effects (JavaScript)
Source: https://docs.swmansion.com/react-native-audio-api/docs/worklets/worklet-processing-node
This example demonstrates how to create a WorkletProcessingNode to implement a simple gain effect. It initializes an AudioContext, defines a worklet function for gain adjustment, and connects the nodes in an audio graph. Dependencies include react-native-audio-api and react-native-worklets.
```javascript
import { AudioContext, AudioRecorder } from 'react-native-audio-api';
// This example shows how to create a simple gain effect using WorkletProcessingNode
function App() {
const recorder = new AudioRecorder({
sampleRate: 16000,
bufferLengthInSamples: 16000,
});
const audioContext = new AudioContext({ sampleRate: 16000 });
// Create a simple gain worklet that multiplies the input by a gain value
const gainWorklet = (
inputData: Array,
outputData: Array,
framesToProcess: number,
currentTime: number
) => {
'worklet';
const gain = 0.5; // 50% volume
for (let ch = 0; ch < inputData.length; ch++) {
const input = inputData[ch];
const output = outputData[ch];
for (let i = 0; i < framesToProcess; i++) {
output[i] = input[i] * gain;
}
}
};
const workletProcessingNode = audioContext.createWorkletProcessingNode(
gainWorklet,
'AudioRuntime'
);
const adapterNode = audioContext.createRecorderAdapter();
adapterNode.connect(workletProcessingNode);
workletProcessingNode.connect(audioContext.destination);
recorder.connect(adapterNode);
recorder.start();
}
```
--------------------------------
### Process Audio Data with Callbacks in React Native Audio API
Source: https://docs.swmansion.com/react-native-audio-api/docs/inputs/audio-recorder
This example shows how to process incoming audio data in real-time using the `onAudioReady` callback from the React Native Audio API. It configures the audio buffer properties like sample rate and channel count, and provides a callback function to handle the audio data chunks. This is useful for streaming or analyzing audio as it's being recorded.
```javascript
import React, { useState, useEffect } from 'react';
import { View, Pressable, Text } from 'react-native';
import { AudioRecorder, AudioManager } from 'react-native-audio-api';
AudioManager.setAudioSessionOptions({
iosCategory: 'record',
iosMode: 'default',
iosOptions: [],
});
const audioRecorder = new AudioRecorder();
const sampleRate = 16000;
const MyRecorder: React.FC = () => {
const [isRecording, setIsRecording] = useState(false);
useEffect(() => {
audioRecorder.onAudioReady(
{
sampleRate,
bufferLength: sampleRate * 0.1, // 0.1s of audio each batch
channelCount: 1,
},
({ buffer, numFrames, when }) => {
// do something with the data, i.e. stream it
}
);
return () => {
audioRecorder.clearOnAudioReady();
};
}, []);
const onStart = async () => {
if (isRecording) {
return;
}
// Make sure the permissions are granted
const permissions = await AudioManager.requestRecordingPermissions();
if (permissions !== 'Granted') {
console.warn('Permissions are not granted');
return;
}
// Activate audio session
const success = await AudioManager.setAudioSessionActivity(true);
if (!success) {
console.warn('Could not activate the audio session');
return;
}
const result = audioRecorder.start();
if (result.status === 'error') {
console.warn(result.message);
return;
}
setIsRecording(true);
};
const onStop = () => {
if (!isRecording) {
return;
}
audioRecorder.stop();
setIsRecording(false);
AudioManager.setAudioSessionActivity(false);
};
return (
{isRecording ? 'Stop' : 'Record'}
);
};
export default MyRecorder;
```
--------------------------------
### createRecorderAdapter
Source: https://docs.swmansion.com/react-native-audio-api/docs/core/base-audio-context
Creates a RecorderAdapterNode for audio recording.
```APIDOC
## POST /createRecorderAdapter
### Description
Creates a `RecorderAdapterNode`.
### Method
POST
### Endpoint
/createRecorderAdapter
### Parameters
### Request Body
```json
{
"type": "RecorderAdapterNode"
}
```
### Response
#### Success Response (200)
- **node** (RecorderAdapterNode) - The created RecorderAdapterNode.
#### Response Example
```json
{
"node": "RecorderAdapterNode"
}
```
```
--------------------------------
### AudioBuffer Constructor
Source: https://docs.swmansion.com/react-native-audio-api/docs/sources/audio-buffer
Creates a new AudioBuffer with a specified number of channels, length, and sample rate.
```APIDOC
## BaseAudioContext.createBuffer(numChannels, length, sampleRate)
### Description
Creates a new `AudioBuffer` object with the specified number of channels, length (in samples), and sample rate.
### Method
`createBuffer`
### Endpoint
N/A (This is a constructor method)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```javascript
const myBuffer = audioContext.createBuffer(2, audioContext.sampleRate * 3, audioContext.sampleRate);
```
### Response
#### Success Response (200)
- **AudioBuffer** (object) - A newly created `AudioBuffer` object.
#### Response Example
```json
{
"type": "AudioBuffer"
}
```
```
--------------------------------
### Create and Use WorkletSourceNode for Sine Wave Generation
Source: https://docs.swmansion.com/react-native-audio-api/docs/worklets/worklet-source-node
Demonstrates creating an AudioContext, defining a sine wave worklet function, instantiating WorkletSourceNode, connecting it to the destination, and controlling playback with start() and stop(). This example requires 'react-native-audio-api'.
```javascript
import { AudioContext } from 'react-native-audio-api';
function App() {
const audioContext = new AudioContext({ sampleRate: 44100 });
// Create a simple sine wave generator worklet
const sineWaveWorklet = (
audioData: Array,
framesToProcess: number,
currentTime: number,
startOffset: number
) => {
'worklet';
const frequency = 440; // A4 note
const sampleRate = 44100;
// Generate audio for each channel
for (let channel = 0; channel < audioData.length; channel++) {
for (let i = 0; i < framesToProcess; i++) {
// Calculate the absolute time for this sample
const sampleTime = currentTime + (startOffset + i) / sampleRate;
// Generate sine wave
const phase = 2 * Math.PI * frequency * sampleTime;
audioData[channel][i] = Math.sin(phase) * 0.5; // 50% volume
}
}
};
const workletSourceNode = audioContext.createWorkletSourceNode(
sineWaveWorklet,
'AudioRuntime'
);
// Connect to output and start playback
workletSourceNode.connect(audioContext.destination);
workletSourceNode.start(); // Start immediately
// Stop after 2 seconds
setTimeout(() => {
workletSourceNode.stop();
}, 2000);
}
```
--------------------------------
### React Component for OscillatorNode - TypeScript
Source: https://docs.swmansion.com/react-native-audio-api/docs/sources/oscillator-node
This example shows a React component that initializes an AudioContext and creates an OscillatorNode. It connects the oscillator to the audio context's destination and starts it. It utilizes the useRef hook for managing the AudioContext instance.
```typescript
import React, { useRef } from 'react';
import {
AudioContext,
OscillatorNode,
} from 'react-native-audio-api';
function App() {
const audioContextRef = useRef(null);
if (!audioContextRef.current) {
audioContextRef.current = new AudioContext();
}
const oscillator = audioContextRef.current.createOscillator();
oscillator.connect(audioContextRef.current.destination);
oscillator.start(audioContextRef.current.currentTime);
}
```
--------------------------------
### Node Creation Methods
Source: https://docs.swmansion.com/react-native-audio-api/docs/core/base-audio-context
Methods for creating various audio processing nodes within the audio context.
```APIDOC
## Node Creation Methods
### `createAnalyser()`
- **Description**: Creates an `AnalyserNode`.
- **Returns**: `AnalyserNode`.
### `createBiquadFilter()`
- **Description**: Creates a `BiquadFilterNode`.
- **Returns**: `BiquadFilterNode`.
### `createBuffer(numOfChannels, length, sampleRate)`
- **Description**: Creates an `AudioBuffer`.
- **Parameters**:
- `numOfChannels` (number): An integer representing the number of channels of the buffer.
- `length` (number): An integer representing the length of the buffer in sampleFrames. Two seconds buffer has length equals to `2 * sampleRate`.
- `sampleRate` (number): A float representing the sample rate of the buffer.
- **Errors**:
- `NotSupportedError`: `numOfChannels` is outside the nominal range [1, 32].
- `NotSupportedError`: `sampleRate` is outside the nominal range [8000, 96000].
- `NotSupportedError`: `length` is less than 1.
- **Returns**: `AudioBuffer`.
### `createBufferSource(options)`
- **Description**: Creates an `AudioBufferSourceNode`.
- **Parameters**:
- `options` (AudioBufferBaseSourceNodeOptions, optional): Dictionary object that specifies if pitch correction has to be available.
- **Returns**: `AudioBufferSourceNode`.
### `createBufferQueueSource(options)`
- **Description**: Creates an `AudioBufferQueueSourceNode`. (Mobile only)
- **Parameters**:
- `options` (AudioBufferBaseSourceNodeOptions, optional): Dictionary object that specifies if pitch correction has to be available.
- **Returns**: `AudioBufferQueueSourceNode`.
### `createConstantSource()`
- **Description**: Creates a `ConstantSourceNode`.
- **Returns**: `ConstantSourceNode`.
### `createConvolver(options)`
- **Description**: Creates a `ConvolverNode`.
- **Parameters**:
- `options` (ConvolverNodeOptions, optional): Dictionary object that specifies associated buffer and normalization.
- **Errors**:
- `NotSupportedError`: `numOfChannels` of buffer is not 1, 2 or 4.
- **Returns**: `ConvolverNode`.
### `createDelay(maxDelayTime)`
- **Description**: Creates a `DelayNode`.
- **Parameters**:
- `maxDelayTime` (number, optional): Maximum amount of time to buffer delayed values.
- **Returns**: `DelayNode`.
### `createGain()`
- **Description**: Creates a `GainNode`.
- **Returns**: `GainNode`.
### `createIIRFilter(options)`
- **Description**: Creates an `IIRFilterNode`.
- **Parameters**:
- `options` (IIRFilterNodeOptions): Dictionary object that specifies the feedforward (numerator) and feedback (denominator) coefficients for the transfer function of the IIR filter.
- **Errors**:
- `NotSupportedError`: One or both of the input arrays exceeds 20 members.
- `InvalidStateError`: All of the feedforward coefficients are 0, or the first feedback coefficient is 0.
- **Returns**: `IIRFilterNode`.
```
--------------------------------
### Create Worklet Source Node (Mobile Only)
Source: https://docs.swmansion.com/react-native-audio-api/docs/core/base-audio-context
Creates a WorkletSourceNode for mobile, designed to execute a worklet and potentially serve as an audio source. It requires the worklet and runtime.
```javascript
this.audioContext.createWorkletSourceNode(worklet, workletRuntime);
```
--------------------------------
### Implement Custom Audio Processor Node Logic (C++)
Source: https://docs.swmansion.com/react-native-audio-api/docs/guides/create-your-own-effect
This C++ file provides the implementation for the `MyProcessorNode`. The constructor initializes the `gain` to 0.5 and sets `isInitialized_` to true. The `processNode` method iterates through each channel and applies the `gain` multiplier to every audio sample.
```cpp
#include "MyProcessorNode.h"
#include
#include
namespace audioapi {
MyProcessorNode::MyProcessorNode(BaseAudioContext *context)
: AudioNode(context), gain(0.5) {
isInitialized_ = true;
}
void MyProcessorNode::processNode(const std::shared_ptr &bus,
int framesToProcess) {
for (int channel = 0; channel < bus->getNumberOfChannels(); ++channel) {
auto *audioArray = bus->getChannel(channel);
for (size_t i = 0; i < framesToProcess; ++i) {
// Apply gain to each sample in the audio array
(*audioArray)[i] *= gain;
}
}
}
} // namespace audioapi
```
--------------------------------
### Create and Configure AnalyserNode for Audio Data (React Native)
Source: https://docs.swmansion.com/react-native-audio-api/docs/guides/see-your-sound
This snippet demonstrates how to initialize an AudioContext, create an AnalyserNode, configure its properties like FFT size and smoothing, and connect it to the audio output. It also includes fetching and decoding an audio buffer for playback.
```typescript
import {
AudioContext,
AudioBuffer,
AudioBufferSourceNode,
AnalyserNode,
} from 'react-native-audio-api';
import React, { useState, useRef, useEffect } from 'react';
import { View, Button, ActivityIndicator } from 'react-native';
const FFT_SIZE = 512;
const AudioVisualizer: React.FC = () => {
const [isPlaying, setIsPlaying] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const [times, setTimes] = useState(new Uint8Array(FFT_SIZE).fill(127));
const [freqs, setFreqs] = useState(new Uint8Array(FFT_SIZE / 2).fill(0));
const audioContextRef = useRef(null);
const bufferSourceRef = useRef(null);
const audioBufferRef = useRef(null);
const analyserRef = useRef(null);
const handlePlayPause = () => {
if (isPlaying) {
bufferSourceRef.current?.stop();
} else {
if (!audioContextRef.current || !analyserRef.current) {
return;
}
bufferSourceRef.current = audioContextRef.current.createBufferSource();
bufferSourceRef.current.buffer = audioBufferRef.current;
bufferSourceRef.current.connect(analyserRef.current);
bufferSourceRef.current.start();
requestAnimationFrame(draw);
}
setIsPlaying((prev) => !prev);
};
const draw = () => {
if (!analyserRef.current) {
return;
}
const timesArrayLength = analyserRef.current.fftSize;
const frequencyArrayLength = analyserRef.current.frequencyBinCount;
const timesArray = new Uint8Array(timesArrayLength);
analyserRef.current.getByteTimeDomainData(timesArray);
setTimes(timesArray);
const freqsArray = new Uint8Array(frequencyArrayLength);
analyserRef.current.getByteFrequencyData(freqsArray);
setFreqs(freqsArray);
requestAnimationFrame(draw);
};
useEffect(() => {
if (!audioContextRef.current) {
audioContextRef.current = new AudioContext();
}
if (!analyserRef.current) {
analyserRef.current = audioContextRef.current.createAnalyser();
analyserRef.current.fftSize = FFT_SIZE;
analyserRef.current.smoothingTimeConstant = 0.8;
analyserRef.current.connect(audioContextRef.current.destination);
}
const fetchBuffer = async () => {
setIsLoading(true);
audioBufferRef.current = await fetch('https://software-mansion.github.io/react-native-audio-api/audio/music/example-music-02.mp3')
.then((response) => response.arrayBuffer())
.then((arrayBuffer) =>
audioContextRef.current!.decodeAudioData(arrayBuffer)
);
setIsLoading(false);
};
fetchBuffer();
return () => {
audioContextRef.current?.close();
};
}, []);
return (
{isLoading && }
);
};
export default AudioVisualizer;
```
--------------------------------
### AnalyserNode Constructor
Source: https://docs.swmansion.com/react-native-audio-api/docs/analysis/analyser-node
Creates a new AnalyserNode instance. This node is used to analyze audio signals.
```APIDOC
## Constructor
`BaseAudioContext.createAnalyser()`
### Description
Creates and returns a new `AnalyserNode` object. This node can be used to analyze audio signals in both the time and frequency domains.
### Method
`createAnalyser()`
### Endpoint
N/A (This is a constructor method, not an HTTP endpoint)
### Parameters
None
### Request Example
```javascript
const audioContext = new (window.AudioContext || window.webkitAudioContext)();
const analyserNode = audioContext.createAnalyser();
```
### Response
#### Success Response
- **AnalyserNode** (object) - A new AnalyserNode instance.
```
--------------------------------
### Create Worklet Processing Node (Mobile Only)
Source: https://docs.swmansion.com/react-native-audio-api/docs/core/base-audio-context
Creates a WorkletProcessingNode for mobile, enabling audio processing via a worklet. It takes the worklet, output buffer, and runtime as parameters.
```javascript
this.audioContext.createWorkletProcessingNode(worklet, outputBuffer, workletRuntime);
```
--------------------------------
### Get Latency and Schedule Playback - JavaScript
Source: https://docs.swmansion.com/react-native-audio-api/docs/sources/audio-buffer-base-source-node
Demonstrates how to get the playback latency of an audio source node and schedule playback with latency compensation. This is useful for precise audio timing.
```javascript
const source = audioContext.createBufferSource({ pitchCorrection: true });
source.buffer = buffer;
source.connect(audioContext.destination);
const latency = source.getLatency();
// Schedule playback slightly earlier to compensate for latency
const startTime = audioContext.currentTime + 1.0; // play in 1 second
source.start(startTime - latency);
```
--------------------------------
### createWaveShaper
Source: https://docs.swmansion.com/react-native-audio-api/docs/core/base-audio-context
Creates a WaveShaperNode for audio signal shaping.
```APIDOC
## POST /createWaveShaper
### Description
Creates a `WaveShaperNode`.
### Method
POST
### Endpoint
/createWaveShaper
### Parameters
### Request Body
```json
{
"type": "WaveShaperNode"
}
```
### Response
#### Success Response (200)
- **node** (WaveShaperNode) - The created WaveShaperNode.
#### Response Example
```json
{
"node": "WaveShaperNode"
}
```
```
--------------------------------
### ADSR Envelope Example with GainNode
Source: https://docs.swmansion.com/react-native-audio-api/docs/effects/gain-node
Demonstrates how to use GainNode with exponential rampToValueAtTime for smooth volume changes, simulating an ADSR envelope. This example utilizes AudioContext, OscillatorNode, and GainNode from the react-native-audio-api library.
```javascript
import { AudioContext } from 'react-native-audio-api';
const ctx = new AudioContext();
const osc = ctx.createOscillator();
const gain = ctx.createGain();
osc.connect(gain);
gain.connect(ctx.destination);
const now = ctx.currentTime;
gain.gain.setValueAtTime(0.00001, now);
// Attack -> peak at 1.00s
gain.gain.exponentialRampToValueAtTime(1, now + 1.00);
// Decay -> to sustain 0.50 at +1.00s
gain.gain.exponentialRampToValueAtTime(0.50001, now + 2.00);
// Immediate release after decay, release duration 2.00s
gain.gain.setValueAtTime(0.50, now + 2.00);
gain.gain.linearRampToValueAtTime(0, now + 4.00);
osc.start(now);
osc.stop(now + 4.00);
```
--------------------------------
### StreamerNode API
Source: https://docs.swmansion.com/react-native-audio-api/docs/sources/streamer-node
The StreamerNode is an AudioScheduledSourceNode that decodes and plays HLS data. It can only be started once.
```APIDOC
## StreamerNode
### Description
The `StreamerNode` is an `AudioScheduledSourceNode` which represents a node that can decode and play Http Live Streaming data. Similar to all of `AudioScheduledSourceNodes`, it can be started only once. If you want to play the same sound again you have to create a new one.
### Constructor
`BaseAudioContext.createStreamer()`
### Methods
#### `initialize(streamPath: string)`
Initializes the streamer with a link to an external HLS source.
**Parameters**
- **streamPath** (string) - Required - Link pointing to an external HLS source
**Returns**
- boolean - Indicating if setup of streaming has worked.
### Request Example
```javascript
import React, { useRef } from 'react';
import {
AudioContext,
StreamerNode,
} from 'react-native-audio-api';
function App() {
const audioContextRef = useRef(null);
if (!audioContextRef.current) {
audioContextRef.current = new AudioContext();
}
const streamer = audioContextRef.current.createStreamer();
streamer.initialize('link/to/your/hls/source');
streamer.connect(audioContextRef.current.destination);
streamer.start(audioContextRef.current.currentTime);
}
```
### Properties
`StreamerNode` does not define any additional properties. It inherits all properties from `AudioScheduledSourceNode`.
```
--------------------------------
### Initialize AudioRecorder
Source: https://docs.swmansion.com/react-native-audio-api/docs/inputs/audio-recorder
Creates a new instance of the AudioRecorder. It's recommended to use a single instance for optimal performance and resource management.
```javascript
import { AudioRecorder } from 'react-native-audio-api';
const audioRecorder = new AudioRecorder();
```
--------------------------------
### Get Current Recording Duration
Source: https://docs.swmansion.com/react-native-audio-api/docs/inputs/audio-recorder
Returns the current duration of the recording in seconds, but only if file output is enabled.
```javascript
const duration = audioRecorder.getCurrentDuration();
```