DEV Community

shyam manek
shyam manek

Posted on • Updated on

React Native Vision Camera library to capture and record videos

Step 1: Create a new React Native project

Run the following command to create a new React Native project:

npx react-native init VisionCameraExample

Step 2: Install dependencies

npm install react-native-vision-camera react-native-video react-native-fs react-native-permissions

Step 3: Link the dependencies

Link the installed dependencies to your project

npx react-native link react-native-video
npx react-native link react-native-fs
npx react-native link react-native-permissions

Enter fullscreen mode Exit fullscreen mode

Step 4: Update AndroidManifest.xml

Open android/app/src/main/AndroidManifest.xml and add the following permissions

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Step 5: Create a CameraScreen component

Create a new file called CameraScreen.js in the src directory with the following code

import React, { useState, useRef } from 'react';
import {
  View,
  TouchableOpacity,
  Text,
  StyleSheet
} from 'react-native';
import { Camera, FileSystem, Permissions } from 'react-native-vision-camera';
import Video from 'react-native-video';

const CameraScreen = () => {
  const [isRecording, setIsRecording] = useState(false);
  const [videoPath, setVideoPath] = useState('');
  const cameraRef = useRef();

  const startRecording = async () => {
    const hasPermission = await requestCameraPermission();
    if (!hasPermission) return;

    setIsRecording(true);

    const videoPath = `${FileSystem.cacheDirectory}/video.mp4`;
    setVideoPath(videoPath);

    cameraRef.current.startRecording({
      quality: '720p',
      videoBitrate: 2000000,
      maxDuration: 10, // Set the maximum duration in seconds (optional)
      maxFileSize: 100 * 1024 * 1024, // Set the maximum file size in bytes (optional)
      outputPath: videoPath,
    });
  };

  const stopRecording = async () => {
    setIsRecording(false);
    await cameraRef.current.stopRecording();
  };

  const requestCameraPermission = async () => {
    const { status } = await Permissions.requestMultiple([
      Permissions.PERMISSIONS.ANDROID.CAMERA,
      Permissions.PERMISSIONS.ANDROID.RECORD_AUDIO,
      Permissions.PERMISSIONS.ANDROID.WRITE_EXTERNAL_STORAGE,
    ]);
    return (
      status[Permissions.PERMISSIONS.ANDROID.CAMERA] === 'granted' &&
      status[Permissions.PERMISSIONS.ANDROID.RECORD_AUDIO] === 'granted' &&
      status[Permissions.PERMISSIONS.ANDROID.WRITE_EXTERNAL_STORAGE] === 'granted'
    );
  };

  return (
    <View style={styles.container}>
      <Camera style={styles.camera} ref={cameraRef} />

      {isRecording ? (
        <TouchableOpacity style={styles.recordButton} onPress={stopRecording}>
          <Text style={styles.recordButtonText}>Stop Recording</Text>
        </TouchableOpacity>
      ) : (
        <TouchableOpacity style={styles.recordButton} onPress={startRecording}>
          <Text style={styles.recordButtonText}>Start Recording</Text>
        </TouchableOpacity>
      )}

      {videoPath !== '' && (
        <View style={styles.videoPlayer}>
          <Video source={{ uri: videoPath }} style={styles.videoPlayer} controls />
        </View>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#000',
  },
  camera: {
    flex: 1,
  },
  recordButton: {
    position: 'absolute',
    bottom: 20,
    left: 20,
    right: 20,
    backgroundColor: 'red',
    padding: 20,
    alignItems: 'center',
  },
  recordButtonText: {
    fontSize: 18,
    color: '#fff',
  },
  videoPlayer: {
    flex: 1,
    marginTop: 20,
  },
});

export default CameraScreen;

Enter fullscreen mode Exit fullscreen mode

Step 6: Update App.js

Replace the contents of App.js with the following code:

import React from 'react';
import CameraScreen from './src/CameraScreen';

const App = () => {
  return <CameraScreen />;
};

export default App;

Enter fullscreen mode Exit fullscreen mode

Step 7: Run the app

Connect your device or start an emulator, then run the following command to start the app:

npx react-native run-android

Enter fullscreen mode Exit fullscreen mode

Make sure your device has the necessary permissions granted for the app to access the camera, record audio, and write to external storage.

The app should now open and display a camera preview. Press the "Start Recording" button to start recording a video, and press "Stop Recording" to stop. The recorded video will be displayed below the camera preview.

Top comments (2)

Collapse
 
davidfeldt profile image
David Feldt πŸ‡ΊπŸ‡¦

Nice post - thanks.

One issue:
cameraRef.current.record({...}) should be cameraRef.current.startRecording({...})

Collapse
 
shyammanek profile image
shyam manek

sorry its my bad