获取`MediaPlayer:错误(1,-2147483648)`尝试立即从SD卡创建后播放视频文件

时间:2015-03-27 08:05:12

标签: android video android-camera android-mediaplayer video-recording

我已经从同一个问题中读过许多答案,例如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"。但这种方式不是我想要的。

通过参数play video after record video immediately

了解如何FILE_PATH的人

请告诉我,

感谢。

p / s:

  • 我的情况是成功录制视频后直接从SD卡播放视频,而不是从服务器流式传输视频。

  • Android 4.1 - Sony Xperia U.

  • 成功录制视频后,只有我的应用程序无法立即播放视频。如果使用默认的Media Player应用程序(另一个应用程序)播放视频就可以。

  • 另外,请注意,如果使用固定文件路径可以播放现有视频。

错误

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();

1 个答案:

答案 0 :(得分:2)

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

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

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

  • 1文件没有数据[此文件我的APP阅读]

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

p / s:我希望我能帮助解释为什么我们得到这个UNKNOWN_ERROR

对不起,

谢谢。