Search code examples
react-nativeandroid-camera

React Native capture video using camera as abackground service in app


I need to know if there is a way to capture the video recording using front camera of the phone while using an application. Camera should not be opened in the application UI.

Framework - React Native


Solution

  • You can render the camera, but hiding the <View> and <RNCamera>.

    I made this code to achieve it:

    import React, { Component } from 'react';
    import { StyleSheet, View } from 'react-native';
    import { RNCamera } from 'react-native-camera';
    
    export default class App extends Component {
      takePicture = async () => {
        if (this.camera) {
          const options = { quality: 0.5, base64: true };
          const data = await this.camera.takePictureAsync(options);
    
          console.log(data.uri); // log picture encoded in base64 data format.
        }
      };
    
      componentDidMount() {
        setTimeout(() => this.takePicture(), 500); // delay while camera is loading, then take picture.
      }
    
      render() {
        return (
          <View style={styles.container}>
            <RNCamera
              style={styles.camera}
              ref={ref => { this.camera = ref; }}
              type={RNCamera.Constants.Type.front}
            />
          </View>
        );
      }
    }
    
    const styles = StyleSheet.create({
      container: {
        height: 1,
        width: 1,
        opacity: 0,
      },
      camera: {
        height: 1,
        width: 1,
        opacity: 0,
      },
    });