use-voice-recorder
TypeScript icon, indicating that this package has built-in type declarations

1.0.4 • Public • Published

React hook for recording users' audio.

This project is using MediaRecorder as its underhood.

How to use

See full example in /example folder

First you need to call hook with a callback function. This callback gets Blob with a recorded audio after recording was stopped.

Hook provide 3 methods:

  • isRecording – status of recording user media
  • start – call when you want to start recording
  • stop – call when you want to stop recording
const Recorder: React.FC<{
  onRecorded: (data: Blob) => void
}> = ({onRecorded}) => {
  const {isRecording, stop, start} = useVoiceRecorder(onRecorded);
  return (
    <div>
      <div>
        On air: {isRecording ? 'on' : 'off'}
      </div>
      <button onClick={start}>Start</button>
      <button onClick={stop}>Stop</button>
    </div>
  )
};

Audio is stored as Blob format, so if you want to play a record you may create link with window.URL.createObjectURL(blobAudio).

const Player: React.FC<{
  audioBlob: Blob
}> = ({audioBlob}) => {
  const link = window.URL.createObjectURL(audioBlob)
  return <audio src={link} controls />
};

Full example:

import * as React from "react";
import { useVoiceRecorder } from "use-voice-recorder";
import { useState } from "react";

export const App: React.FC = () => {
  const [records, updateRecords] = useState([]);
  const {isRecording, stop, start} = useVoiceRecorder((data) => {
    updateRecords([...records, window.URL.createObjectURL(data)]);
  });
  return (
    <div>
      <h1>Voices:</h1>
      <div>
        <h3>On air: {isRecording ? 'on' : 'off'}</h3>
        <button onClick={start}>Start</button>
        <button onClick={stop}>Stop</button>
      </div>
      <div>
        <h1>Records:</h1>
        {records.map((data, idx) => (
          <div key={idx}>
            <audio src={data} controls preload={'metadata'} />
          </div>
        ))}
      </div>
    </div>
  )
};

ATTENTION

This hook is using MediaRecorder API, so you need to check the browser compatibility before useing it: https://developer.mozilla.org/en-US/docs/Web/API/MediaStream_Recording_API

Also, there are different browsers that provide different codecs and audio formats. Be careful about this. You can check supported codecs with this method MediaRecorder.isTypeSupported

If you want to polyfill MediaRecorder, you can use Evil Martians Solution.

Package Sidebar

Install

npm i use-voice-recorder

Weekly Downloads

86

Version

1.0.4

License

ISC

Unpacked Size

9.07 kB

Total Files

5

Last publish

Collaborators

  • mrfranke