DEV Community

Cover image for How to Record and Upload Your Voice Using React Native! 🎙️✨
Nilesh Kumar
Nilesh Kumar

Posted on

How to Record and Upload Your Voice Using React Native! 🎙️✨

Have you ever thought, “What if I could record my voice and send it to an app to turn it into text?” Well, guess what? Today, we're diving into a simple React Native app that does just that. Even if you're just starting out, this explanation is as easy as pie (or candy 🍬). Let’s explore step by step!

What Does This App Do? 🤔

This app is like a superpower for your phone. It lets you:

  1. Record your voice. 🗣️
  2. Save that recording on your phone. 📂
  3. Upload the recording to a magical website (API) that listens to it and writes down exactly what you said! 💬

The Magic Ingredients (Imports) 🧙‍♂️

Here’s the first step. We bring in some super cool tools to make the app work:

  • **Button**: For recording actions.
  • **react-native-audio-recorder-player**: To record and manage audio.
  • **react-native-fs**: To save the audio file in your phone’s storage.
  • **axios**: To send the recorded audio file to Backend.
import React, { useState } from 'react';
    import {
      Button,
      Platform,
      SafeAreaView,
      ScrollView,
      StatusBar,
      StyleSheet,
      Text,
      View,
    } from 'react-native';
    import AudioRecorderPlayer from 'react-native-audio-recorder-player';
    import RNFS from 'react-native-fs';
Enter fullscreen mode Exit fullscreen mode

Create state for manage recording state

Create state for recording and for file location path

const [recording, setRecording] = useState(false);
    cosnt [f
Enter fullscreen mode Exit fullscreen mode

ilePath, setFilePath] = useState("");

Getting Ready to Record 🎤

Next, we set up the app to record audio. This involves deciding:

  • Where to save the audio file.
  • What format to use (like .mp3 or .m4a).
const audioSet = {
      AudioEncoderAndroid: 'aac', // Audio encoding for Android
      AudioSourceAndroid: 'mic', // Use the microphone
      AVModeIOS: 'measurement',  // iOS audio mode
      AVEncoderAudioQualityKeyIOS: 'high', // High quality for iOS
      AVFormatIDKeyIOS: 'aac', // AAC format for iOS
    };

Enter fullscreen mode Exit fullscreen mode

Start Recording 🎙️

When you press the Start Recording button, the app will:

  1. Find a place to save your voice file.
  2. Start listening and save everything you say.
const startRecording = async () => {
      const dirs = Platform.OS === 'ios' ? RNFS.DocumentDirectoryPath : RNFS.ExternalDirectoryPath;
      const path = Platform.select({
        ios: `${dirs}/hello.m4a`,
        android: `${dirs}/hello.mp3`,
      });
      const result = await audioRecorderPlayer.startRecorder(path, audioSet, true);
      setRecording(true);
      setFilePath(result);
      console.log('Recording started at: ', result);
    };

Enter fullscreen mode Exit fullscreen mode

Stop Recording 🛑

Once you press Stop Recording, the app will:

  1. Stop listening.
  2. Save the recording.
  3. Upload it to an online API that will write down what you said.
 const stopRecording = async () => {
      const result = await audioRecorderPlayer.stopRecorder();
      setRecording(false);
      console.log('Recording saved at: ', result);
      uploadAudio(filePath); // Upload the saved file
    };
Enter fullscreen mode Exit fullscreen mode

Upload Your Voice to the Cloud 🌩️

Now comes the fun part! The app sends your recording to a magical brain on the internet (API) that listens and writes your words into text.

  const uploadAudio = async (filePath) => {
      const file = {
        uri: `file://${filePath}`,
        type: 'audio/aac',
        name: 'audio.aac',
      };
      const formData = new FormData();
      formData.append('audio_file', file);
      formData.append('lang', "en-US");
      try {
        const response = await fetch('https://your-api-url/speech-to-text', {
          method: 'POST',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'multipart/form-data',
            'Authorization': `Bearer YOUR_API_TOKEN`,
          },
          body: formData,
        });
        const result = await response.json();
        console.log('Upload success: ', result);
      } catch (error) {
        console.error('Upload failed: ', error);
      }
    };
Enter fullscreen mode Exit fullscreen mode

The App Layout 🖥️

Here’s the UI code that connects everything:

  • A Button: To toggle between Start and Stop recording.
  • A Text: To show where the file is saved.
return (
      <SafeAreaView>
        <StatusBar />
        <ScrollView>
          <View style={{ marginTop: 50 }}>
            <Button
              title={recording ? "Stop Recording" : "Start Recording"}
              onPress={recording ? stopRecording : startRecording}
            />
            {filePath ? <Text>File saved at: {filePath}</Text> : null}
          </View>
        </ScrollView>
      </SafeAreaView>
    );
Enter fullscreen mode Exit fullscreen mode

Complete code

Below is the complete working code that we discussed in the blog, showcasing how to build a voice recording app in React Native. It includes functionality to record audio, save the file, and upload it to an API for speech-to-text conversion. This code brings together everything we talked about, from setting up the recording environment to managing the app's UI and integrating with a cloud service, providing a fully functional and ready-to-use solution.

This hook for recording.

import RNFS from 'react-native-fs';
    import AudioRecorderPlayer, {
      AVEncoderAudioQualityIOSType,
      AVEncodingOption,
      AVModeIOSOption,
      AudioEncoderAndroidType,
      AudioSourceAndroidType,
      OutputFormatAndroidType,
    } from 'react-native-audio-recorder-player';
    import { useState } from 'react';
    import { Platform } from 'react-native';
    const audioRecorderPlayer = new AudioRecorderPlayer();
    audioRecorderPlayer.setSubscriptionDuration(0.1);
    const useRecording = () => {
      const [recording, setRecording] = useState(false);
      const [recordingPath, setRecordingPath] = useState('');
      const audioSet = {
        AudioEncoderAndroid: AudioEncoderAndroidType.AAC,
        AudioSourceAndroid: AudioSourceAndroidType.MIC,
        AVModeIOS: AVModeIOSOption.measurement,
        AVEncoderAudioQualityKeyIOS: AVEncoderAudioQualityIOSType.high,
        AVNumberOfChannelsKeyIOS: 2,
        AVFormatIDKeyIOS: AVEncodingOption.aac,
        OutputFormatAndroid: OutputFormatAndroidType.AAC_ADTS,
      };
      const startRecording = async () => {
        const dirs =
          Platform.OS === 'ios'
            ? RNFS.DocumentDirectoryPath
            : RNFS.ExternalDirectoryPath;
        console.log('dir', dirs);
        const path = Platform.select({
          ios: `${dirs}hello.m4a`,
          android: `${dirs}/hello.mp3`,
        }); // File name for your recording
        console.log('Recorded File Path:', path);
        const result = await audioRecorderPlayer.startRecorder(
          path,
          audioSet,
          true,
        );
        console.log('result', result);
        setRecording(true);
        setRecordingPath(result);
      };
      const stopRecording = async () => {
        const result = await audioRecorderPlayer.stopRecorder();
        setRecording(false);
      };
      return {
        startRecording,
        stopRecording,
        setRecording,
        recording, 
        recordingPath,
      }
    };
    export default useRecording;
Enter fullscreen mode Exit fullscreen mode

This is for upload

const axios = require('axios');
    const uploadAudio = async (audioFilePath) => {
        try{
            const file = {
                uri: `file://${audioFilePath}`,
                type: 'audio/mp3',
                name: 'audio.mp3',
              };
            const header = {'Content-Type': 'multipart/form-data'};
            const formData = new FormData();
            // formData.append('audio', file);
            formData.append('audio_file', file);
            let config = {
                method: 'post',
                maxBodyLength: Infinity,
                url: 'Your api URL',
                headers: { 
                  'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNzM0MDk0MDk0LCJpYXQiOjE3MzQwMDc2OTQsImp0aSI6IjFmMDc2ZDIyMWM2NTQwMDJiMWMwMGU3MjAyODYzMTk2IiwidXNlcl9pZCI6OTZ9.LrBr-Yuy6sDanMuRTrU_EIxgmcYBzmmLtDcMrO1Sft8', 
                  header
                },
                data : formData
              };
              axios.request(config)
              .then((response) => {
                console.log(JSON.stringify(response.data));
              })
              .catch((error) => {
                console.log(error);
              });
        }catch(err){
            console.log(err);
        }finally{
            // console.log("finally speech to text")
        }
    }
Enter fullscreen mode Exit fullscreen mode

This is for UI design.

return (
      <SafeAreaView>
        <StatusBar />
        <ScrollView>
          <View>
            <Button
              title={recording ? "Stop Recording" : "Start Recording"}
              onPress={recording ? stopRecording : startRecording}
            />
            {filePath ? <Text>File saved at: {filePath}</Text> : null}
          </View>
        </ScrollView>
      </SafeAreaView>
    );
Enter fullscreen mode Exit fullscreen mode

Why is This App Awesome? 💡

  • Fun for Everyone: Kids, teens, and adults can record their voices.
  • Super Useful: Turn your spoken words into text without typing!
  • Simple Design: Easy-to-use button for recording and stopping.

Conclusion

Building a voice recording and speech-to-text app in React Native is not only fun but also a great learning experience! This project showcases the power of combining simple UI components with advanced features like audio recording and API integration. By following this guide, you've learned how to record audio, save it locally, and upload it for processing. Whether you're using this app for productivity, creativity, or just experimenting, the possibilities are endless. Keep exploring, keep coding, and let your imagination turn ideas into reality! 🚀

Top comments (0)