DEV Community

Cover image for Posting Audio Recordings to Your Web App Database as Blob Datatypes
Ian Iversen
Ian Iversen

Posted on

1

Posting Audio Recordings to Your Web App Database as Blob Datatypes

The goal is to receive audio from the users microphone to and store that audio on a database. To do this, we first need to ask the user, in their browser if we can use their microphone.

const [trackOne, setTrackOne] = useState(
    {
      isRecording: false,
      blobURL: '',
      isBlocked: false,
    })

  // one time check for mic permissions
  useEffect(() => {
    navigator.getUserMedia({ audio: true },
      () => {
        console.log('Permission Granted');
        setTrackOne({ isBlocked: false });
      },
      () => {
        console.log('Permission Denied');
        setTrackOne({ isBlocked: true })
      },
    );

  }, [])
Enter fullscreen mode Exit fullscreen mode

Once permission is granted, a function can be called to start the recording.

  const startOne = (e) => {
    if (trackOne.isBlocked) {
      console.log('Permission Denied');
    } else {
      Mp3Recorder
        .start()
        .then(() => {
          setTrackOne({ isRecording: true });
        }).catch((e) => console.error(e));
    }
  };
Enter fullscreen mode Exit fullscreen mode

In order to stop the recording a function must be called that stops the recording.

const stopOne = () => {
    Mp3Recorder
      .stop()
      .getMp3()
      .then(([buffer, blob]) => {
        const file = new File(buffer, 'track-one.mp3', {
          type: audioType
        })
        setAudioData(file)
        const blobURL = URL.createObjectURL(blob)
        setTrackOne({ blobURL, isRecording: false })
      })
  }
Enter fullscreen mode Exit fullscreen mode

Then a useEffect can be used to post the data whenever the stop button is clicked.

const formData = new FormData()
  formData.append('audio_data', audioData)

  useEffect(()=>{
    fetch('/tracks', {
      method: 'POST',
      body: formData,
    })
    .then((r) => {
      if (r.ok) {
        fetch('/tracks')
        .then(r => r.json())
        .then(data => setAllTracks(data))
      }
    })
  }, [audioData])
Enter fullscreen mode Exit fullscreen mode

The included fetch GET request at the end is to immediately render the new track.

libraries involved:
import MicRecorder from 'mic-recorder-to-mp3';

important
A bit rate must be set in your audio recording component
const Mp3Recorder = new MicRecorder({ bitRate: 128 });

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)