Audio recorder and play back in React JS

Audio recording and playback using React JS

Posted by Luke Beeno on July 4, 2021

In this demo you will be shown how to create an audio recorder and play back using React JS.

If you don't have a React project created, before you continue you can go https://wecode101.com/create-react-app here to understand how.

Create a components directory within src directory and add the file audio.component.js within the components directory.

In order to view audio.component.js edit App.js within the src directory. 

The Audio component is imported, along with CSS Bootstrap for styling to App.js which is the App Component.  The App Component is the main component in React which acts as a container for all other components.

import React, { Component } from "react";

import "bootstrap/dist/css/bootstrap.min.css";

import Audio from "./components/audio.component";

class App extends Component {

  render() {

    return (

      <Audio/>

    );
  }
}
export default App;

In the Audio component the mic-recorder-to-mp3 is used to import the audio widget. The buttons next to the audio widget are used to control the recording and playback.

There are comments within the block of code below that will explain what is happening.

import React, { Component } from "react";

import MicRecorder from 'mic-recorder-to-mp3';

const Mp3Recorder = new MicRecorder({ bitRate: 128 });

export default class Audio extends Component {

  constructor(props) {

    super(props);

    /*    

     * declare states that will enable and disable  

     * buttons that controls the audio widget

     */

    this.state = {

        isRecording: false,

        blobURL: '',

        isBlocked: false,

        isRecordingStp: false,

      }

    //binds the methods to the component

    this.start = this.start.bind(this);

    this.stop = this.stop.bind(this);

    this.reset = this.reset.bind(this);

   }

  componentDidMount(){

    //Prompt the user for permission to allow audio device in browser

    navigator.getUserMedia = (

      navigator.getUserMedia ||

      navigator.webkitGetUserMedia ||

      navigator.mozGetUserMedia ||

      navigator.msGetUserMedia

     );

     //Detects the action on user click to allow or deny permission of audio device

     navigator.getUserMedia({ audio: true },

      () => {

        console.log('Permission Granted');

        this.setState({ isBlocked: false });

      },

      () => {

        console.log('Permission Denied');

        this.setState({ isBlocked: true })

      },

    );

  }

  start(){

    /*  

     * If the user denys permission to use the audio device

     * in the browser no recording can be done and an alert is shown

     * If the user allows permission the recoding will begin

     */

    if (this.state.isBlocked) {

      alert('Permission Denied');

    } else {

      Mp3Recorder

        .start()

        .then(() => {

          this.setState({ isRecording: true });

        }).catch((e) => console.error(e));

    }

  }

  stop() {

     /*

     * Once the recoding starts the stop button is activated

     * Click stop once recording as finished  

     * An MP3 is generated for the user to download the audio

     */

    Mp3Recorder

      .stop()

      .getMp3()

      .then(([buffer, blob]) => {

        const blobURL = URL.createObjectURL(blob)

        this.setState({ blobURL, isRecording: false });

        this.setState({ isRecordingStp: true });

      }).catch((e) => console.log(e));

  };

  reset() {

      /*    

       * The user can reset the audio recording  

       * once the stop button is clicked    

       */

      document.getElementsByTagName('audio')[0].src = '';

      this.setState({ isRecordingStp: false });

  };

  render() {

    //display view of audio widget and control buttons

    return(

  <div className="row d-flex justify-content-center mt-5">

  <button className="btn btn-light" onClick={this.start} disabled={this.state.isRecording}>Record</button>

  <button className="btn btn-danger" onClick={this.stop} disabled={!this.state.isRecording}>Stop</button>

  <button className="btn btn-warning" onClick={this.reset} disabled={!this.state.isRecordingStp}>Reset</button>

  <audio src={this.state.blobURL} controls="controls" />

  </div>

    );

  }

}

This is a very quick and easy way to allow audio functionality within your web app. This component can potential be used within a UI in order to add audio functionality.

 If you wish to download this tutorial go to https://github.com/wecode101/audio-recoding-and-play-back-with-React-js