Search code examples
androidandroid-camera

Camera preview is black when using getExternalStorageDirectory to save the video


I'm capture video using camera2 API and Google sample code.

I come up against an issue when I trying change output location to be saved on the sdcard/MyApp/filename instead Android/data/my_package/filename.

Here is the method:

private File getVideoFile(Context context) {
    // Not working, cause black preview
    return new File(Environment.getExternalStorageDirectory().getPath() +
                                                    "/myApp/", "myVideo.mp4");
    // Working
    return new File(context.getExternalFilesDir(null), "myVideo.mp4");
}

So, my question, why saving the video on the sdcard cause "Black preview" and how can I save the video on the sdcard ?

Edit

Here is the permission I ask:

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

Solution

  • Finally I found the solution.

    I don't know why it's like this, but the preview is blank when the target directory is not exist.

    I save the video in myApp directory that wasn't exist yet, that's cause the preview to be blank.

    The solution is to create the directory first and just than to save the video. The code should be like this:

    private File getVideoFile(Context context) {
        File folder = new File (Environment.getExternalStorageDirectory().getPath() + "/myApp/");
        folder.mkdirs();
        return new File(Environment.getExternalStorageDirectory().getPath() + "/myApp/", "myVideo.mp4");
    }