react-native-vision-camera icon indicating copy to clipboard operation
react-native-vision-camera copied to clipboard

🐛 Error when starting recording: `java.io.IOException: prepare failed`

Open 0xSigma-dev opened this issue 1 year ago • 7 comments

What's happening?

i want to start recording a video but it fails with an error

Reproduceable Code

import React, { useState, useEffect, useRef } from 'react';
import { View, Text, SafeAreaView, ActivityIndicator, StyleSheet, ScrollView, Image, TouchableOpacity } from 'react-native';
import { Camera, useCameraDevice, useCameraPermission, useMicrophonePermission } from 'react-native-vision-camera';
import { height, styles as sx, width } from '../helpers/styles';
import { logo } from '../assets/exports';


export default function FaceScanComponent() {
  const [cameraPermission, setCameraPermission] = useState<'pending' | 'authorized' | 'denied'>('pending');
  const { hasPermission: cameraHasPermission, requestPermission: requestCameraPermission } = useCameraPermission();
  const { hasPermission: microphoneHasPermission, requestPermission: requestMicrophonePermission } = useMicrophonePermission();
  const [isRecording, setIsRecording] = useState(false);

  useEffect(() => {
    const requestPermissions = async () => {
      const cameraStatus = await requestCameraPermission();
      const microphoneStatus = await requestMicrophonePermission();

      if (cameraStatus === true && microphoneStatus === true) {
        setCameraPermission('authorized');
      } else {
        setCameraPermission('denied');
      }
    };

    requestPermissions();
  }, [requestCameraPermission, requestMicrophonePermission]);

  const device = useCameraDevice('front');
  const camera = useRef<Camera>(null)

  

  if (device == null) return <NoCameraDeviceError />;

  const startRecording = async () => {
    if (camera.current) {
      camera.current.startRecording({
        onRecordingFinished: async (video) => {
          const path = video.path;
        },
        videoBitRate: 'low',
        videoCodec: 'h265',
        onRecordingError: (error) => console.error(error),
      });
      setIsRecording(true);
    }
  };
  
  


  const stopRecording = () => {
    if (camera.current) {
      camera.current.stopRecording();
      setIsRecording(false);
    }
  };

  function renderDetectorContent() {
    if (device && cameraPermission === 'authorized') {
      return (
        <>
          <Camera ref={camera} style={styles.camera} device={device} isActive={true} video={true} audio={true} />
          <View style={styles.buttonContainer}>
            <TouchableOpacity onPress={isRecording ? stopRecording : startRecording} style={styles.recordButton}>
              <Text style={styles.recordButtonText}>{isRecording ? 'Stop Recording' : 'Start Recording'}</Text>
            </TouchableOpacity>
          </View>
        </>
      );
    } else if (cameraPermission === 'denied') {
      return <Text style={styles.errorText}>No camera permission.</Text>;
    }
    return <ActivityIndicator style={styles.loading} size="large" color="#1C6758" />;
  }



  return (
    <SafeAreaView >
      <ScrollView contentContainerStyle={[styles.body]}>
      <Image
        source={logo}
        style={styles.logo}
      />
      
      <View style={styles.container}>
      <SafeAreaView style={styles.header}>
        <Text style={styles.headerText}>React Native Image Detector</Text>
      </SafeAreaView>

      <View style={styles.caption}>
        <Text style={styles.captionText}>Welcome To React-Native-Vision-Camera Tutorial</Text>
      </View>

      {renderDetectorContent()}

      <View style={styles.caption}>
        <Text style={styles.captionText}>Welcome To React-Native-Vision-Camera Tutorial</Text>
      </View>

    </View>

     
      
</ScrollView>
    </SafeAreaView>
  );
}

Relevant log output

ERROR  {"cause": {"message": "prepare failed.", "stacktrace": "java.io.IOException: prepare failed.
	at android.media.MediaRecorder._prepare(Native Method)
	at android.media.MediaRecorder.prepare(MediaRecorder.java:1377)
	at com.mrousavy.camera.core.RecordingSession.start(RecordingSession.kt:92)
	at com.mrousavy.camera.core.CameraSession.startRecording(CameraSession.kt:647)
	at com.mrousavy.camera.CameraView_RecordVideoKt.startRecording(CameraView+RecordVideo.kt:36)
	at com.mrousavy.camera.CameraViewModule$startRecording$1.invokeSuspend(CameraViewModule.kt:91)
	at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
	at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
	at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:584)
	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:793)
	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:697)
	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:684)
"}, "code": "capture/unknown", "message": "An unknown error occurred while trying to start a video recording! prepare failed.", "userInfo": null}

Camera Device

{
  "formats": [],
  "sensorOrientation": "landscape-left",
  "hardwareLevel": "full",
  "maxZoom": 10,
  "minZoom": 1,
  "maxExposure": 24,
  "supportsLowLightBoost": false,
  "neutralZoom": 1,
  "physicalDevices": [
    "wide-angle-camera"
  ],
  "supportsFocus": true,
  "supportsRawCapture": true,
  "isMultiCam": false,
  "minFocusDistance": 0,
  "minExposure": -24,
  "name": "FRONT (1)",
  "hasFlash": false,
  "hasTorch": false,
  "position": "front",
  "id": "1"
}

Device

Xiaomi Redmi Note 12

VisionCamera Version

3.8.2

Can you reproduce this issue in the VisionCamera Example app?

Yes, I can reproduce the same issue in the Example app here

Additional information

0xSigma-dev avatar Jan 25 '24 20:01 0xSigma-dev

Hey - does it work if you remove the videoBitRate and videoCodec options?

mrousavy avatar Jan 26 '24 08:01 mrousavy

no same error i actually added the videoBitRate and videoCodec options to see if it would work

0xSigma-dev avatar Jan 26 '24 09:01 0xSigma-dev

Hm. Can you please upload the full adb logcat logs, not just the error? (e.g. to gist.github.com) I wanna see what happened before that.

mrousavy avatar Jan 26 '24 09:01 mrousavy

i'm not exactly sure how to get what you asked for

0xSigma-dev avatar Jan 26 '24 10:01 0xSigma-dev

Run the app in Android Studio, there's a logcat window. Also the issue template tells you how to do that

mrousavy avatar Jan 26 '24 10:01 mrousavy

Hey - did you try to run the app in Android studio yet so I can see the logs?

mrousavy avatar Jan 30 '24 16:01 mrousavy

@mrousavy I have the same issue. When i hit the startRecording function my app suddenly crashes. I have check and this issue came on android 11. When i use android 13 it works fine.

Is there any solution that i can run this package on android 10,11,12,13 and 14.

MuhammadFaisal215 avatar Feb 01 '24 06:02 MuhammadFaisal215

Hey! I just released a new V4 beta (v4.0.0-beta.7) where I fixed a bunch of issues! 💪🚀 Can you test that and see if that fixes the issue for you? 😅

yarn add react-native-vision-camera@beta

You might need to increase the compileSdk to the newest Android SDK (34) if you are behind.

mrousavy avatar Mar 19 '24 10:03 mrousavy

@mrousavy I was also getting a "java.io.IOException: prepare failed" error but on OnePlus Nord CE 2 when I tried to record. I have just upgraded to beta.8 and the issue has now been resolved 🎉 thank you very much for everything.

aharwood9 avatar Mar 19 '24 12:03 aharwood9

Great to hear that V4 now works perfectly! If you appreciate my work, please consider 💖 sponsoring me on GitHub 💖 so I can keep maintaining this library, fixing bugs and building new features! :)

mrousavy avatar Mar 25 '24 09:03 mrousavy

Hey - I think this issue has been fixed in VisionCamera 4.0.0. 🥳

Please try V4 and let me know if you still experience this issue;

  • if not, please consider 💖 sponsoring me on GitHub 💖 to support the development of VisionCamera and thank me for my time spent on fixing bugs and building new features.
  • if you still see this issue, please comment and we can re-open this. But please update your native logs with the native (Xcode/Android Studio) logs from running VisionCamera V4 so I can investigate this.

mrousavy avatar Apr 22 '24 11:04 mrousavy