Android Studio - 无法从相机捕捉视频

Android Studio - Unable to capture video from Camera

我正在尝试通过图库或相机捕捉视频。我能够成功地从图库中获取视频。但是,当我尝试从相机录制视频时,它丢失了轨道,我无法获取路径。它确实将视频保存在路径上。日志给出以下 error/warning。为什么录像机失去踪迹?我哪里错了?

2022-03-15 07:32:08.683 14318-14318/com.example.locationfetcher_v2 W/MirrorManager: this model don't Support
2022-03-15 07:32:13.864 14318-14318/com.example.locationfetcher_v2 D/DecorView: createDecorCaptionView windowingMode:1 mWindowMode 1 isFullscreen: true
2022-03-15 07:32:14.875 14318-14318/com.example.locationfetcher_v2 I/Timeline: Timeline: Activity_launch_request time:174742145
2022-03-15 07:32:14.912 14318-14395/com.example.locationfetcher_v2 D/OpenGLRenderer: endAllActiveAnimators on 0xb400007e4ade6e00 (AlertController$RecycleListView) with handle 0xb400007e52639220
2022-03-15 07:32:20.913 14318-14339/com.example.locationfetcher_v2 W/System: A resource failed to call close

这是我的代码:

public void showPictureDialog(View view){
        AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);
        pictureDialog.setTitle("Select Action");
        String[] pictureDialogItems = {
                "Select video from gallery",
                "Record video from camera" };
        pictureDialog.setItems(pictureDialogItems,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0:
                                chooseVideoFromGallery();
                                break;
                            case 1:
                                takeVideoFromCamera();
                                break;
                        }
                    }
                });
        pictureDialog.show();
    }


    public void chooseVideoFromGallery() {
        Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);

        startActivityForResult(galleryIntent, PICK_VIDEO_GALLERY);
    }

    private void takeVideoFromCamera() {
        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
        startActivity(intent);
    }

    public String getPath(Uri uri) {
        String[] projection = { MediaStore.Video.Media.DATA };
        Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
        if (cursor != null) {
            // HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
            // THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
            int column_index = cursor
                    .getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } else
            return null;
    }

    private void saveVideoToInternalStorage (String filePath) {

        File newfile;

        try {

            File currentFile = new File(filePath);
//            show_notification("New File Video:" + Environment.getExternalStorageDirectory());
            File wallpaperDirectory = new File(Environment.getExternalStorageDirectory() + VIDEO_DIRECTORY);
            newfile = new File(wallpaperDirectory, Calendar.getInstance().getTimeInMillis() + ".mp4");

            if (!wallpaperDirectory.exists()) {
                wallpaperDirectory.mkdirs();
            }

            if(currentFile.exists()){

                InputStream in = new FileInputStream(currentFile);
                OutputStream out = new FileOutputStream(newfile);

                // Copy the bits from instream to outstream
                byte[] buf = new byte[1024];
                int len;

                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                in.close();
                out.close();
                show_notification("Video file saved successfully.");
            }else{
                show_notification("Video saving failed. Source file missing.");
            }
        } catch (Exception e) {
            show_notification(e.toString());
            e.printStackTrace();
        }

@RequiresApi(api = Build.VERSION_CODES.Q)
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        inputStreamImg = null;
        if (requestCode == PICK_VIDEO_GALLERY){
            if (data != null) {
                Uri contentURI = data.getData();

                String selectedVideoPath = getPath(contentURI);
                Log.d("path",selectedVideoPath);
//                show_notification("Saving...");
                saveVideoToInternalStorage(selectedVideoPath);
                vidView.setVideoURI(contentURI);
                vidView.requestFocus();
                vidView.start();
                videoPath = selectedVideoPath;
                show_notification("video Gallery - " + videoPath);
            } else if (requestCode == PICK_VIDEO_CAMERA) {
                Uri contentURI = data.getData();
                show_notification(contentURI.getPath());
                String recordedVideoPath = getPath(contentURI);
                show_notification(recordedVideoPath);
                saveVideoToInternalStorage(recordedVideoPath);

                videoPath = recordedVideoPath;

                vidView.setVideoURI(contentURI);
                vidView.requestFocus();
                vidView.start();
                show_notification("video Camera - " + videoPath);
            }
        }
    }

我不知道它是否有帮助,但也许你应该做 startActivityForResult 或 ActivtyResultLauncher。如果我有足够的声誉,我会评论。

你给你添加记录权限了吗android清单

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

此外,

当目标不等于 Build.VERSION_CODES.Q

时,您可以删除这个@RequiresApi(api = Build.VERSION_CODES.Q) 或处理情况吗
@RequiresApi(api = Build.VERSION_CODES.Q)
@Override
public void onActivityResult{

由于以下错误,您无法获取视频路径:

1.In 您的 takeVideoFromCamera() 方法您使用 startActivity(intent); 而不是 startActivityForResult(intent, PICK_VIDEO_CAMERA); 启动意图,因此无法调用 onActivityResult() 来检索视频路径.所以你必须像下面这样更改你的代码:

private void takeVideoFromCamera() {
    Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
    intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
    startActivityForResult(intent, PICK_VIDEO_CAMERA);
}

2.After 您进行了上述更改 onActivityResult() 被正确调用但是您没有处理正确的响应,因为 requestCode == PICK_VIDEO_CAMERA 的语句在 [=19= 的语句中].所以你必须像下面这样修改它:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == Activity.RESULT_OK) 
    {
        if (requestCode == PICK_VIDEO_GALLERY) {
            if (data != null) {
                Uri contentURI = data.getData();
                vidView.setVideoURI(contentURI);
                vidView.start();
            }
        }
        else if (requestCode == PICK_VIDEO_CAMERA) {
            if (data != null) {
                Uri contentURI = data.getData();
                vidView.setVideoURI(contentURI);
                vidView.start();
            }
        }
    }
}

因为 startActivityForResult() 现在已被弃用,我建议使用新的标准方式 ActivityResultContracts.StartActivityForResult() 来更改它,方法是将您的代码修改为如下所示:

private void takeVideoFromCamera() {
    Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
    intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
    if (getPackageManager().resolveActivity(intent, 0) != null) {
        videoActivityResultLauncher.launch(intent);
    } else {
        Toast.makeText(this, "No apps supports this action", Toast.LENGTH_SHORT).show();
    }
}

private final ActivityResultLauncher<Intent> videoActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
    @Override
    public void onActivityResult(ActivityResult result) {
        if (result.getResultCode() == Activity.RESULT_OK && result.getData() != null) {
            Uri contentURI = result.getData().getData();
            vidView.setVideoURI(contentURI);
            vidView.start();
        }
    }
});