立即从 SD 卡创建后尝试播放视频文件时出现“MediaPlayer:错误(1,-2147483648)”

Get `MediaPlayer﹕ error (1, -2147483648)` when try to play video file after created immediately from sd card

我已经阅读了很多相同问题的答案,例如 the answer for same question but looks like still not find out the solution from sturrockad

我现在正在 Custom Camera with Recording video feature

我可以take picture and then review picture correctly.

但是有issue with record video and then review video immediately.

我想play video after record video immediately通过参数FILE_PATH,不在下次打开应用程序。

我已经试过了:

1 - 扫描为 Android 安装的媒体,系统识别出出现新文件。

2 - 试试put fixed File Path, it worked,可以玩。 "/mnt/sdcard/Pictures/Enterprise/VID_20150327_143003.mp4"。但是这样不是我想要的。

知道如何通过参数 FILE_PATH

play video after record video immediately 的人

请告诉我,

谢谢。

p/s :

错误

MediaPlayer﹕ error (1, -2147483648) MediaPlayer﹕ Error (1,-2147483648)

LOGCAT

I/ExternalStorage﹕ Scanned             /mnt/sdcard/Pictures/Enterprise/VID_20150327_153645.mp4:
I/ExternalStorage﹕ -> uri=content://media/external/video/media/21992
I/﹕ FILE_PATH /mnt/sdcard/Pictures/Enterprise/VID_20150327_153645.mp4
E/MediaPlayer﹕ error (1, -2147483648)
E/MediaPlayer﹕ Error (1,-2147483648)

编辑 我得到了答案。谢谢。

代码播放视频下方

private void showVideoOnUI() {
    Log.i("", "FILE_PATH " + FILE_PATH);

    // THIS LINE SHOW THE VIDEO TOTALLY CAN BE PLAYED
    //        mVvVideo.setVideoPath("/mnt/sdcard/Pictures/Enterprise/VID_20150327_143003.mp4");

    // ------- ERROR HAPPEN IN THIS LINE ---------
    // FILE PATH = /mnt/sdcard/Pictures/Enterprise/VID_20150327_143555.mp4 also,
    // BUT THE VIDEO TOTALLY CAN NOT BE PLAYED
    mVvVideo.setVideoPath(FILE_PATH);
    //        mVvVideo.setVideoURI(Uri.parse(FILE_PATH));

    // set play video view dialog details photo
    MediaController mMc = new MediaController(getActivity());
    mMc.setAnchorView(mVvVideo);
    mMc.setMediaPlayer(mVvVideo);

    mVvVideo.requestFocus();
    mVvVideo.setBackgroundColor(Color.WHITE);
    mVvVideo.setMediaController(mMc);
    mVvVideo.setZOrderOnTop(true);
    mVvVideo.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (mVvVideo.isPlaying()) {
                mVvVideo.pause();

                // Show full-screen button again
                mVvVideo.setVisibility(View.VISIBLE);
            } else {
                mVvVideo.start();
            }

            return false;
        }
    });

    if (!mVvVideo.isPlaying())
        mVvVideo.start();
}

下面是创建后查看新文件的代码扫描媒体

/**
 * Create a File for saving an image or video
 */
private File getOutputMediaFile(int type) {
    // To be safe, you should check that the SDCard is mounted
    // using Environment.getExternalStorageState() before doing this.
    File mediaStorageDir = new File(
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), define.Camera.ENTERPRISE);

    // This location works best if you want the created images to be shared
    // between applications and persist after your app has been uninstalled.

    // Create the storage directory if it does not exist
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            Log.i("", "failed to create directory");
            return null;
        }
    }

    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    File mediaFile = null;
    if (type == MediaType.PHOTO) {
        mediaFile = new File(
                mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + Extension.JPG);
    } else if (type == MediaType.VIDEO) {
        mediaFile = new File(
                mediaStorageDir.getPath() + File.separator + "VID_" + timeStamp + Extension.MP4);
    }

    String FILE_PATH = mediaFile.getAbsolutePath();
    // todo Should refresh Sd card in here
    File mFile = new File(FILE_PATH);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        File f = new File(mFile.getAbsolutePath(), mFile.getName());
        Uri contentUri = Uri.fromFile(f);

        Log.i("", "contentUri - " + contentUri.toString());

        mediaScanIntent.setData(contentUri);
        getActivity().sendBroadcast(mediaScanIntent);
    } else {
        getActivity().sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory() + "/" + mFile.getParent())));
    }

    // Tell the media scanner about the new file so that it is
    // immediately available to the user.
    MediaScannerConnection.scanFile(getActivity(),
            new String[]{FILE_PATH}, null,
            new MediaScannerConnection.OnScanCompletedListener() {
                public void onScanCompleted(String path, Uri uri) {
                    // ExternalStorage﹕ Scanned /mnt/sdcard/Pictures/Enterprise/VID_20150327_151212.mp4:
                    Log.i("ExternalStorage", "Scanned " + path + ":");
                    // ExternalStorage﹕ -> uri=content://media/external/video/media/21973
                    Log.i("ExternalStorage", "-> uri=" + uri);
                }
            });
    return mediaFile;
}

这是MANIFEST.XML文件

<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />

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

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme">

    <activity
        android:name=".Enterprise"
        android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity
        android:name="ui.activity.CustomCamera"
        android:screenOrientation="portrait"
        android:exported="true">

        <intent-filter>
            <action android:name="android.intent.action.MEDIA_MOUNTED" />
            <data android:scheme="file"/>
        </intent-filter>

    </activity>
    <activity android:name="ui.activity.CustomGallery" />

</application>

此处是从录制视频页面转移到查看页面的代码[正确]

/**
                 * Record video mode
                 */
                // Begin Record video

                // Configure MediaRecorder
                if (IS_RECORDING_VIDEO) {
                    Log.i("", "Stop recording video");

                    try {
                        // stop recording and release camera
                        // stop the recording
                        CustomCamera.mMediaRecorder.stop();

                        // release the MediaRecorder object
                        CustomCamera.releaseMediaRecorder();
                        // take camera access back from MediaRecorder
                        CustomCamera.mCamera.lock();

                        // inform the user that recording has stopped
                        IS_RECORDING_VIDEO = false;

                        // Stop the preview before transfer to Review page
                        CustomCamera.mCamera.stopPreview();

                        // Should release Camera for the next time can be used
                        CustomCamera.releaseCamera();

                        // Transfer to Review page to see Recording video at there
                        // Send the file path also
                        ((FragmentActivity) getActivity())
                                .getSupportFragmentManager().beginTransaction()
                                .addToBackStack(null)
                                .replace(
                                        R.id.fl_custom_camera,
                                        CameraReviewFragment.newInstance(
                                                getOutputMediaFile(MediaType.VIDEO).getAbsolutePath()))
                                .commitAllowingStateLoss();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    // initialize video camera
                    if (prepareVideoRecorder(define.Camera.CAMERA_BACK)) {
                        Log.i("", "Start recording video");

                        // Camera is available and unlocked, MediaRecorder is prepared,
                        // now you can start recording
                        CustomCamera.mMediaRecorder.start();

                        // inform the user that recording has started
                        IS_RECORDING_VIDEO = true;

                        // Begin set Recording time in here
                        //start the countDown
                        mCdt.start();
                    } else {
                        // prepare didn't work, release the camera
                        CustomCamera.releaseMediaRecorder();
                    }
                }

此处设置录制视频的代码

private boolean prepareVideoRecorder(int mode){
    // Should release before use new Preview for Recording Video mode
    CustomCamera.releaseCamera();

    // Initialize camera
    CustomCamera.mCamera = CustomCamera.getCameraInstance(mode);

    // Set orientation display
    CustomCamera.setCameraDisplayOrientation(getActivity(), mode);

    // Should release before use new Preview for Recording Video mode
    CustomCamera.releaseMediaRecorder();

    CustomCamera.mMediaRecorder = new MediaRecorder();

    // Step 1: Unlock and set camera to MediaRecorder
    CustomCamera.mCamera.unlock();
    CustomCamera.mMediaRecorder.setCamera(CustomCamera.mCamera);

    // Step 2: Set sources
    CustomCamera.mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
    CustomCamera.mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

    // todo Step 3: Set a CamcorderProfile (requires API Level 8 or higher)
    CustomCamera.mMediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_LOW));
    //        CustomCamera.mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);

    //        CustomCamera.mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
    //        CustomCamera.mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);

    // Step 4: Set output file
    CustomCamera.mMediaRecorder.setOutputFile(getOutputMediaFile(MediaType.VIDEO).toString());

    // Step 5: Set the preview output
    CustomCamera.mMediaRecorder.setPreviewDisplay(mCameraPreview.getHolder().getSurface());

    // Step 6: Prepare configured MediaRecorder
    try {
        CustomCamera.mMediaRecorder.prepare();
    } catch (IllegalStateException e) {
        e.printStackTrace();
        CustomCamera.releaseMediaRecorder();
        return false;
    } catch (IOException e) {
        e.printStackTrace();
        CustomCamera.releaseMediaRecorder();
        return false;
    }
    return true;
}

终于我认清了自己的错。对不起所有人。我需要编辑如下代码

// Step 3: Set a CamcorderProfile (requires API Level 8 or higher)
    CustomCamera.mMediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));

    // Step 4: Set output file
    RECORDED_FILE_PATH = getOutputMediaFile(MediaType.VIDEO).toString();
    CustomCamera.mMediaRecorder.setOutputFile(RECORDED_FILE_PATH);

// Transfer to Review page to see Recording video at there
                        // Send the file path also
                        ((FragmentActivity) getActivity())
                                .getSupportFragmentManager().beginTransaction()
                                .addToBackStack(null)
                                .replace(R.id.fl_custom_camera,
                                        CameraReviewFragment.newInstance(RECORDED_FILE_PATH))
                                .commitAllowingStateLoss();

好的,我现在找到了解决方案。

这是我的错。我调用了 getOutputMediaFile() 方法 2 次,所以它创建了 2 个文件:

  • 1 文件有数据通过流传输。 [此文件我的应用未读]

  • 1 文件没有数据[这个文件我的应用程序已读]

因此,显示了 video can not play 对话框,我也得到了这个错误 MediaPlayer﹕ error (1, -2147483648)

p/s : 我希望我贡献原因解释为什么我们得到这个 UNKNOWN_ERROR.

对不起大家,

谢谢。