DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How to Build Scalable Mobile Apps With React Native: A Step-by-Step Guide
  • How to Build a React Native Chat App for Android
  • Optimizing User Experience in React Native
  • Cross-Platform Mobile Application Development: Evaluating Flutter, React Native, HTML5, Xamarin, and Other Frameworks

Trending

  • Beyond Linguistics: Real-Time Domain Event Mapping with WebSocket and Spring Boot
  • A Modern Stack for Building Scalable Systems
  • Streamlining Event Data in Event-Driven Ansible
  • GDPR Compliance With .NET: Securing Data the Right Way
  1. DZone
  2. Coding
  3. JavaScript
  4. How to Record Audio in React Native

How to Record Audio in React Native

By 
krissanawatt kaewsanmunag user avatar
krissanawatt kaewsanmunag
·
Updated Sep. 02, 20 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
26.5K Views

Join the DZone community and get the full member experience.

Join For Free

In this tutorial, we are going to learn how to record and play audio in React Native apps. We are going to build a simple screen that supports features such as recording audio, playing audio files, pausing and resuming, as well as resetting audio streams. The final app will look like the image below.

Recording and playing audio in mobile applications is a very popular feature. Fortunately, to record and play audio in React Native apps can be done easily. This is thanks to the Expo ecosystem that easily supports sound recording to React Native. However, if we need to add any feature that requires us to migrate off the Expo system to React Native CLI, we may need to put much more effort into its configuration.

As a result, we may need to use a third-party package. After much research, I have come up with a package that meets our requirements for recording and playing audio in React Native. The package name is react-native-audio-recorder-player. The package is easy to configure and provides us with robust modules and components to implement an audio recorder and player in React Native applications.

Without further ado, let’s get started!

Prerequisites

In order to go through this tutorial, we need to first prepare our React Native development environment.

Installing and Setting Up the Package

First, we need to install the react-native-audio-recorder-player package using yarn or npm. I prefer using yarn so I am going to use yarn and run the following command in the project Terminal:

Shell
 




x


 
1
yarn add react-native-audio-recorder-player



Then, we need to run the following command in order to run the app in the iOS device or simulator (simply replace ios with android if you are running on Android)

Shell
 




xxxxxxxxxx
1


 
1
react-native run-ios


Preparing the Recorder Component

Here, we start by importing the necessary methods from the react-native-audio-recorder-player package as shown in the code snippet below:

JavaScript
 




xxxxxxxxxx
1


 
1
import AudioRecorderPlayer, {
2
 AVEncoderAudioQualityIOSType,
3
 AVEncodingOption,
4
 AudioEncoderAndroidType,
5
 AudioSet,
6
 AudioSourceAndroidType,
7
} from 'react-native-audio-recorder-player';



Then, we need to create a few new states and also initialize a new recorder instance as depicted in the code snippet below:

JavaScript
 




xxxxxxxxxx
1
16


 
1
class App extends Component {
2
 
          
3
  constructor(props) {
4
    super(props);
5
    this.state = {
6
      isLoggingIn: false,
7
      recordSecs: 0,
8
      recordTime: '00:00:00',
9
      currentPositionSec: 0,
10
      currentDurationSec: 0,
11
      playTime: '00:00:00',
12
      duration: '00:00:00',
13
    };
14
    this.audioRecorderPlayer = new AudioRecorderPlayer();
15
    this.audioRecorderPlayer.setSubscriptionDuration(0.09); // optional. Default is 0.1
16
  }


Preparing the UI

For the UI implementation, we are going to use components of the react-native-paper package. We already have an idea of how an audio player and recorder should look like. Hence, we can easily implement it on our screen. For a simple UI layout for the app, we can use the code from the following code snippet:

JavaScript
 




xxxxxxxxxx
1
40


 
1
return (
2
      <Card style={{ flex: 1, flexDirection: 'row', alignItems: 'center', alignContent: 'center', alignSelf: 'center' }}>
3
        <Background>
4
          <Logo />
5
          <Header>InstaPlayer</Header>
6
          <Title>{this.state.recordTime}</Title>
7
          <Button mode="contained" icon="record" onPress={() => this.onStartRecord()}>
8
            RECORD
9
        </Button>
10
 
          
11
          <Button
12
            icon="stop"
13
            mode="outlined"
14
            onPress={() => this.onStopRecord()}
15
          >
16
            STOP
17
    </Button>
18
          <Divider />
19
          <Title>{this.state.playTime} / {this.state.duration}</Title>
20
          <Button mode="contained" icon="play" onPress={() => this.onStartPlay()}>
21
            PLAY
22
        </Button>
23
 
          
24
          <Button
25
            icon="pause"
26
            mode="contained"
27
            onPress={() => this.onPausePlay()}
28
          >
29
            PAUSE
30
    </Button>
31
          <Button
32
            icon="stop"
33
            mode="outlined"
34
            onPress={() => this.onStopPlay()}
35
          >
36
            STOP
37
    </Button>
38
        </Background>
39
      </Card>
40
    )



Hence, we will get an audio recorder and an audio player on the same screen as displayed in the simulator screenshot below:

Initial screenshot

Now, it is time to implement the functions for each button on the screen.

Record Audio in React Native

The first thing we need to do in any recording app is to implement the recording feature. The actual implementation is fairly simple for this. We need to follow these simple steps:

  1. Firstly, we start by defining an audio file name and extension.
  2. Secondly, we define the audio format preference.
  3. Lastly, we start to record audio and add a record time to the state.

The implementation for this is provided in the code snippet below:

JavaScript
 




xxxxxxxxxx
1
22


 
1
onStartRecord = async () => {
2
    
3
    const path = 'hello.m4a';
4
    const audioSet = {
5
      AudioEncoderAndroid: AudioEncoderAndroidType.AAC,
6
      AudioSourceAndroid: AudioSourceAndroidType.MIC,
7
      AVEncoderAudioQualityKeyIOS: AVEncoderAudioQualityIOSType.high,
8
      AVNumberOfChannelsKeyIOS: 2,
9
      AVFormatIDKeyIOS: AVEncodingOption.aac,
10
    };
11
    console.log('audioSet', audioSet);
12
    const uri = await this.audioRecorderPlayer.startRecorder(path, audioSet);
13
    this.audioRecorderPlayer.addRecordBackListener((e) => {
14
      this.setState({
15
        recordSecs: e.current_position,
16
        recordTime: this.audioRecorderPlayer.mmssss(
17
          Math.floor(e.current_position),
18
        ),
19
      });
20
    });
21
    console.log(`uri: ${uri}`);
22
  };



Hence, we will get the result as shown in the demo screenshot of the emulator below (simply press the Record button):

App feature implementation


Here, we can see that the timer starts as we tap on the RECORD button.

Stopping Audio Recording

The stop recording feature is easy to implement as well. We just need to call the stopRecorder method and reset the time counter back to zero using the code from the following code snippet:

JavaScript
 




xxxxxxxxxx
1


 
1
onStopRecord = async () => {
2
    const result = await this.audioRecorderPlayer.stopRecorder();
3
    this.audioRecorderPlayer.removeRecordBackListener();
4
    this.setState({
5
      recordSecs: 0,
6
    });
7
    console.log(result);
8
  };



As you can notice we get the result as shown in the demo screenshot below:

Stopping recording feature


Hence, the timer stops as we tap on the STOP button.

Audio Player to Play Audio in React Native

Since we are done with the recording and stop recording features, we now have an audio file to play. In order to implement the play feature, we need to call the startPlayer method and pass the path to the file that we’ve just recorded. Then, we need to set the volume. Once the audio plays, we need to set a callback function to stop playing when the play counter indicator reaches the completion point. We also need to add current playtime to the state to display the counter properly in the UI. The implementation for this is provided in the code snippet below:

JavaScript
 




xxxxxxxxxx
1
21


 
1
onStartPlay = async (e) => {
2
    console.log('onStartPlay');
3
    const path = 'hello.m4a'
4
    const msg = await this.audioRecorderPlayer.startPlayer(path);
5
    this.audioRecorderPlayer.setVolume(1.0);
6
    console.log(msg);
7
    this.audioRecorderPlayer.addPlayBackListener((e) => {
8
      if (e.current_position === e.duration) {
9
        console.log('finished');
10
        this.audioRecorderPlayer.stopPlayer();
11
      }
12
      this.setState({
13
        currentPositionSec: e.current_position,
14
        currentDurationSec: e.duration,
15
        playTime: this.audioRecorderPlayer.mmssss(
16
          Math.floor(e.current_position),
17
        ),
18
        duration: this.audioRecorderPlayer.mmssss(Math.floor(e.duration)),
19
      });
20
    });
21
  };



Hence, we will get the result as shown in the demo screenshot below:

Playing the audio


As you can see, when we tap the PLAY button, the audio starts playing.

Pausing The Audio Player

Implementing a pause feature is simple. We just need to call the pausePlayer method, when PAUSE button is pressed. We can do this by using the following piece of code:

JavaScript
 




xxxxxxxxxx
1


 
1
onPausePlay = async (e) => {
2
 await this.audioRecorderPlayer.pausePlayer();
3
};



Hence, we will get the result as shown in the demo screenshot below:

Pausing audio playback


Here, we can see that when we hit the PAUSE button the player pauses, and when we hit the Play button again it starts to play from the same point where we stopped it.

Stopping the Audio Player in React Native

In order to stop the player, we need to call the stopPlayer method. Then, we need to remove the playback data by calling removePlayBackListener method and reset the counter to zero again. The feature to trigger the stop action is provided as a function in the code snippet below:

JavaScript
 




xxxxxxxxxx
1


 
1
onStopPlay = async (e) => {
2
 console.log('onStopPlay');
3
 this.audioRecorderPlayer.stopPlayer();
4
 this.audioRecorderPlayer.removePlayBackListener();
5
 };



Hence, we will get the result as shown in the screenshot below:


Here, we can see that when we hit the STOP button the player stops and after hitting the PLAY button, the counter starts from this beginning.

Finally, we have successfully implemented the audio recorder and player in the React Native application along with an intuitive UI layout. Hopefully now you know how to record audio in React Native and how to play the recorded audio files into a React Native audio player.

Conclusion

It has been an interesting feature to get our hands on. Implementing an audio recorder and player in a React Native may sound difficult but in fact, it’s fairly simple thanks to a powerful library. This tutorial provides detailed guidance on each step so that it becomes even simpler. The package that we used for recording and playing audio is pretty robust and easy to implement as well. Make sure to get your hands dirty with it.

React Native React (JavaScript library) Record (computer science)

Published at DZone with permission of krissanawatt kaewsanmunag. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How to Build Scalable Mobile Apps With React Native: A Step-by-Step Guide
  • How to Build a React Native Chat App for Android
  • Optimizing User Experience in React Native
  • Cross-Platform Mobile Application Development: Evaluating Flutter, React Native, HTML5, Xamarin, and Other Frameworks

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!