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:
What an audio codec is
Popular React Native audio libraries & their codec support
Installation & setup
Recording with different codecs
Playback (local files, streaming)
Transcoding & advanced use cases
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
| Library | Recording Codecs | Playback Codecs |
|---|---|---|
| react-native-audio | lpcm, 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)
iOS Info.plist:
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 ..
C. react-native-audio-recorder-player (Modern API)
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 settingsconst 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 recordingawait 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 recordingawait 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);});
// Stopawait 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 streamconst player = new Player('https://server.com/audio.mp3') .prepare(err => { if (!err) player.play(); });
// Pause & resumeplayer.pause();player.play();
// Simple recordingconst recorder = new Recorder('myaudio.mp4') // .mp4→AAC .record();
// Stop & get durationrecorder.stop((err, file) => { console.log('Saved to', file);});```
### 5.2 `react-native-sound` (Playback-only)
```jsimport Sound from 'react-native-sound';
// Load from bundle or URLconst 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
Post a Comment