Android - 视频无法保存

时间:2015-12-06 12:30:03

标签: java android video

我们正在尝试创建一个可以将视频保存到目录的应用。但是,它不会保存为mp4文件而是文件夹!例如,当我录制视频时,它会被保存为文件夹(/ root / DCIM / sdcard / DCIM / Camera App / video.mp4 /)。

以下是我们的代码:

/ **      *视频      * /     // Context context = this;

private boolean prepareMediaRecorder() {
    String path = String.valueOf(getOutputMediaFile(MEDIA_TYPE_VIDEO));
    File file = new File(path, "Eye Spy");
    file.mkdirs();
    mMediaRecorder = new MediaRecorder();


    try {
        mCamera.unlock();
    } catch (Exception ex) {
        return false;
    }


    // adjust the camera the way you need
    mMediaRecorder.setCamera(mCamera);
    mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
    mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);

    //
    CamcorderProfile profile = CamcorderProfile.get(Camera.CameraInfo.CAMERA_FACING_BACK, CamcorderProfile.QUALITY_LOW);
    profile.fileFormat = MediaRecorder.OutputFormat.MPEG_4;
    profile.videoCodec = MediaRecorder.VideoEncoder.MPEG_4_SP;
    profile.videoFrameHeight = 240;
    profile.videoFrameWidth = 320;
    profile.videoBitRate = 15;
    mMediaRecorder.setProfile(profile);
    mMediaRecorder.setPreviewDisplay(mPreview.getSurface());
    mMediaRecorder.setOutputFile(path);

    //set max size
    mMediaRecorder.setMaxDuration(600000); // Set max duration 60 sec.
    mMediaRecorder.setMaxFileSize(50000000); // Set max file size 50M

    try {
        mMediaRecorder.prepare();
    } catch (Exception e) {
        releaseMediaRecorder();
        e.printStackTrace();
    }
    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    Uri contentUri = Uri.fromFile(file);
    mediaScanIntent.setData(contentUri);
    getBaseContext().sendBroadcast(mediaScanIntent);

    return true;
}

private void releaseMediaRecorder() {
    if (mMediaRecorder != null) {
        mMediaRecorder.reset(); // clear recorder configuration
        mMediaRecorder.release(); // release the recorder object
        mMediaRecorder = null;
        if (mCamera != null) {
            mCamera.lock(); // lock camera for later use
        }
    }
}
private Camera.PictureCallback mPicture = new Camera.PictureCallback() {
    @Override
    public void onPictureTaken(byte[] data, Camera camera) {

        File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);

        if (pictureFile == null) {
            Log.i("TRY:", " Error creating media file, check storage permissions:");
            Log.d(TAG, "Error creating media file, check storage permissions: " +
                    e.getMessage());
            return;
        }

        try {
            FileOutputStream fos = new FileOutputStream(pictureFile);
            fos.write(data);
            Toast.makeText(InstagramProfilePage.this, "Picture taken!", Toast.LENGTH_SHORT).show();
            /*loc2Exif(pictureFile);*/
            fos.close();
        } catch (FileNotFoundException e) {
            Log.d(TAG, "File not found: " + e.getMessage());
        } catch (IOException e) {
            Log.d(TAG, "Error accessing file: " + e.getMessage());
        }
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri contentUri = Uri.fromFile(pictureFile);
        mediaScanIntent.setData(contentUri);
        getBaseContext().sendBroadcast(mediaScanIntent);
        mCamera.startPreview();

    }




    /*mCamera.startPreview();*/
};

/**
 * Create a file Uri for saving an image or video
 */
private static Uri getOutputMediaFileUri(int type) {
    return Uri.fromFile(getOutputMediaFile(type));
}

/**
 * Create a File for saving an image or video
 */
private static 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), "Eye Spy");

    // 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.d("Eye Spy", "failed to create directory");
            return null;
        }
    }

    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    File mediaFile;
    if (type == MEDIA_TYPE_IMAGE) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                "IMG_" + timeStamp + ".jpg");
        Log.i("TRY:", " PICTURE SAVED");
    } else if (type == MEDIA_TYPE_VIDEO) {
        mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES), "Eye Spy");
        mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                "VID_" + timeStamp + ".mp4");
    } else {
        Log.i("TRY:", " file = null");
        return null;
    }
    Log.i("TRY:", mediaFile.getPath());
    return mediaFile;
}
 private Camera.PictureCallback mPicture = new Camera.PictureCallback() {
    @Override
    public void onPictureTaken(byte[] data, Camera camera) {

        File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);

        if (pictureFile == null) {
            Log.i("TRY:", " Error creating media file, check storage permissions:");
            Log.d(TAG, "Error creating media file, check storage permissions: " +
                    e.getMessage());
            return;
        }

        try {
            FileOutputStream fos = new FileOutputStream(pictureFile);
            fos.write(data);
            Toast.makeText(InstagramProfilePage.this, "Picture taken!", Toast.LENGTH_SHORT).show();
            /*loc2Exif(pictureFile);*/
            fos.close();
        } catch (FileNotFoundException e) {
            Log.d(TAG, "File not found: " + e.getMessage());
        } catch (IOException e) {
            Log.d(TAG, "Error accessing file: " + e.getMessage());
        }
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri contentUri = Uri.fromFile(pictureFile);
        mediaScanIntent.setData(contentUri);
        getBaseContext().sendBroadcast(mediaScanIntent);
        mCamera.startPreview();

    }




    /*mCamera.startPreview();*/
};

/**
 * Create a file Uri for saving an image or video
 */
private static Uri getOutputMediaFileUri(int type) {
    return Uri.fromFile(getOutputMediaFile(type));
}

/**
 * Create a File for saving an image or video
 */
private static 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), "Eye Spy");

    // 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.d("Eye Spy", "failed to create directory");
            return null;
        }
    }

    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    File mediaFile;
    if (type == MEDIA_TYPE_IMAGE) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                "IMG_" + timeStamp + ".jpg");
        Log.i("TRY:", " PICTURE SAVED");
    } else if (type == MEDIA_TYPE_VIDEO) {
        mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES), "Eye Spy");
        mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                "VID_" + timeStamp + ".mp4");
    } else {
        Log.i("TRY:", " file = null");
        return null;
    }
    Log.i("TRY:", mediaFile.getPath());
    return mediaFile;
}

1 个答案:

答案 0 :(得分:1)

当您在第二行代码上调用getOutputMediaFile(MEDIA_TYPE_VIDEO)时,您将获得.mp4 File,当您将其转换为字符串时:

String path = String.valueOf(getOutputMediaFile(MEDIA_TYPE_VIDEO));

你得到了文件的绝对路径,然后你正在调用file.mkdirs(),它会在该路径之外创建一个文件夹,基本上你是说创建一个文件夹而不是文件。你想要做的是创建文件夹然后创建实际文件。

<强>解决方案

而不是打电话:

file.mkdirs();

使用这行代码创建文件父文件夹:

file.getParentFile().mkdirs();