Skip to main content

React Native Audio Codecs: Deep Dive with Examples

 Working with audio in React Native means understanding both the codecs (formats/encoders) available and the libraries that expose recording/playback APIs. Below is a comprehensive guide covering:

  1. What an audio codec is

  2. Popular React Native audio libraries & their codec support

  3. Installation & setup

  4. Recording with different codecs

  5. Playback (local files, streaming)

  6. Transcoding & advanced use cases

  7. Performance tips & best practices


1. What Is an Audio Codec?

An audio codec is a method for encoding (compressing) and decoding (decompressing) digital audio. Common codecs on mobile include:

  • PCM/WAV (uncompressed, highest quality, large file sizes)

  • AAC (lossy, high quality at moderate bitrates; natively supported by iOS/Android)

  • AMR (optimized for voice; low bitrate)

  • MP3 (ubiquitous but patent-encumbered; usually via third-party libs)

  • Vorbis & Opus (open, efficient; via extra modules on Android only)

Choosing the right codec is a trade-off between quality, file size, licensing, and platform support.

2. Key React Native Audio Libraries & Codecs

LibraryRecording CodecsPlayback Codecs
react-native-audiolpcm, ima4, aac, MAC3/6, ulaw…(playback via companion libs)

react-native-audio-toolkit | .mp4 (AAC), .mp3, .wav, .caf | .mp4 (AAC), .mp3, .wav, streaming react-native-sound | N/A (playback only) | mp3, wav, aac, caf (bundled) react-native-audio-recorder-player | AAC (iOS/Android), AMR-WB, WAV | AAC, WAV, AMR-WB expo-av | AAC (.m4a), WAV, mp3, opus* | AAC, WAV, mp3, opus*

\* MP3 support on Android/iOS may require bundling .mp3 decoders or using Expo's expo-av. \** When built with the appropriate codecs. \*** Web-only (via Web Audio API).

3. Installation & Native Setup

A. react-native-audio (Recording-focused)

npm install react-native-audio --save

iOS Info.plist:

<key>NSMicrophoneUsageDescription</key>
<string>We need your mic for recording audio.</string>

Android AndroidManifest.xml:

<uses-permission android:name="android.permission.RECORD_AUDIO" />

```

### B. react-native-audio-toolkit (Playback + Recording)  

```bash

yarn add react-native-audio-toolkit

cd ios && pod install && cd ..

No additional Android/iOS config needed; uses native modules under the hood.

C. react-native-audio-recorder-player (Modern API)

yarn add react-native-audio-recorder-player

Expo users: must use a development build or EAS, since it has native code.

4. Recording Examples

4.1 Using react-native-audio

import { AudioRecorder, AudioUtils } from 'react-native-audio';

// File path & codec settings
const audioPath = AudioUtils.DocumentDirectoryPath + '/test.aac';
const recordingOptions = {
  SampleRate: 44100,       // 44.1 kHz
  Channels: 1,             // Mono
  AudioQuality: 'High',    // iOS-only: Low, Medium, High
  AudioEncoding: 'aac',    // lpcm, ima4, aac, etc.
  IncludeBase64: false     // large data can impact performance
};

// Prepare & start recording
await AudioRecorder.prepareRecordingAtPath(audioPath, recordingOptions);
AudioRecorder.onProgress = data => {
  console.log('Recording time:', data.currentTime);
};
AudioRecorder.onFinished = data => {
  console.log('Recording finished:', data);
};
await AudioRecorder.startRecording();

// Later… stop recording
await AudioRecorder.stopRecording();

This produces an AAC-encoded .aac file at 44.1 kHz, mono

4.2 Using react-native-audio-recorder-player

import AudioRecorderPlayer from 'react-native-audio-recorder-player';

const audioRecorderPlayer = new AudioRecorderPlayer();
const path = 'hello.wav'; // platform-specific path resolution

// Start recording in WAV (uncompressed)
await audioRecorderPlayer.startRecorder(path, {
  // Options: default is WAV on iOS, AAC on Android
  AudioEncoderAndroid: 'pcm_16bit',
  OutputFormatAndroid: 'wav',
});
audioRecorderPlayer.addRecordBackListener(e => {
  console.log('sec:', e.current_position);
});

// Stop
await audioRecorderPlayer.stopRecorder();
audioRecorderPlayer.removeRecordBackListener();

5. Playback Examples

5.1 react-native-audio-toolkit

import { Player, Recorder } from 'react-native-audio-toolkit';

// Playback an AAC file or remote MP3 stream
const player = new Player('https://server.com/audio.mp3')
  .prepare(err => {
    if (!err) player.play();
  });

// Pause & resume
player.pause();
player.play();


// Simple recording
const recorder = new Recorder('myaudio.mp4') // .mp4→AAC
  .record();

// Stop & get duration
recorder.stop((err, file) => {
  console.log('Saved to', file);
});
```

### 5.2 `react-native-sound` (Playback-only)

```js
import Sound from 'react-native-sound';

// Load from bundle or URL
const sound = new Sound('song.mp3', Sound.MAIN_BUNDLE, err => {
  if (err) return console.warn('Failed loading', err);
  sound.setVolume(0.8);
  sound.play(success => {
    console.log(success ? 'Finished' : 'Playback failed');
    sound.release();
  });
});


6. Transcoding & Advanced Use Cases

  • On-device transcoding (e.g. AAC→MP3, WAV→OPUS) can be handled via native bridges like react-native-ffmpeg or community modules such as [react-native-audio-transcoder].

  • Live audio streaming: use chunked PCM buffers, pass via WebRTC/DataChannel, or stream .mp3/.aac segments over HTTP.

  • Audio effects: integrate DSP libraries (e.g. Superpowered, TarsosDSP) via native modules.

7. Performance Tips & Best Practices

  • Record in chunks to avoid blocking JS.

  • Match sample rate to playback hardware (44.1 kHz or 48 kHz).

  • Use mono (1 channel) for voice; stereo for music only if needed.

  • Avoid base64 transfers—upload files natively if possible.

  • Test on real devices; emulators may not reflect true performance.


Thank You🙏

Comments

Popular posts from this blog

Enhancing React Native Development: A Comprehensive Guide to Redux Toolkit for Efficient State Management

Mobile app development has seen a massive evolution over the years, and React Native is at the forefront of this revolution. If you are a developer aiming to build high-quality mobile applications with robust state management, then learning how to integrate Redux Toolkit with React Native is essential. In this guide, we will deeply explore what Redux Toolkit is, why it matters, how to integrate it into your React Native projects, and best practices to keep your code efficient and simple.   What are React Native and Redux Toolkit? React Native is a popular framework that allows developers to build native mobile apps using JavaScript and React. Its ability to share code across platforms has made it a favorite among startups and established tech giants alike. With React Native, you can create smooth and nimble applications that provide a native look and feel on both iOS and Android devices. Redux Toolkit is a powerful library designed to simplify state management in your applicat...

Mastering Axios in React Native: Your Ultimate Guide to Efficient API Calls

In the world of mobile app development, data is king. Whether you're building a social media feed, a weather app, or an e-commerce store, your React Native application needs to talk to the outside world. It needs to fetch data from servers, send user information, update records, and more. This conversation happens through API calls. While React Native provides a basic `fetch` function for this purpose, many developers prefer a more powerful and user-friendly tool: Axios. If you've ever found network requests confusing or cumbersome, this guide is for you. We'll break down everything you need to know about using Axios in React Native, using simple words and practical examples. What is Axios, and Why Should You Use It in React Native? Let's start with the basics. Axios is a popular, promise-based HTTP client for JavaScript. In simple terms, it's a library that makes it incredibly easy to send requests to web servers and handle their responses. Think of it like this: y...

A Complete Guide to Updating Dependencies in React Native Projects

 Keeping your React Native dependencies up to date is not just about working with the latest features—it's also about improving performance, patching vulnerabilities, and maintaining long-term project stability. Over time, dependencies can lag behind, leading to compatibility issues, warning floods in the console, or deprecated methods. This guide will walk you through a strategic and foolproof method to upgrade every dependency inside your package.json, focusing on real-world React Native workflows. ✨ Why Keep Dependencies Updated?  Before diving into the technical steps, let’s talk about why upgrading matters: Security Fixes: Older versions may expose your app to known security risks. Performance Improvements: Newer libraries often come with optimizations and smaller bundle sizes. Compatibility: Keeping pace with React Native’s fast release cycle minimizes integration pains later. Access to New Features: You benefit from improvements in syntax, components, and APIs. 📦 Overv...