使用android驱动器api成功上传但文件已损坏

时间:2015-08-12 10:29:42

标签: android video file-upload mp4 google-drive-android-api

这是我用于捕获视频7秒的代码,然后使用Google Drive Android API自动将视频上传到Google云端硬盘。问题是:上传完成后,我无法播放视频。可以播放智能手机中保存的视频,但不能播放上传的视频。

public class Video extends 
AppCompatActivity implements 
SurfaceHolder.Callback, GoogleApiClient.ConnectionCallbacks, 
GoogleApiClient.OnConnectionFailedListener 
{

    public static File file;
    public static GoogleApiClient mGoogleApiClient;
    MediaRecorder recorder;
    SurfaceHolder holder;
    boolean recording = false;
    FileOutputStream fileOut;
    public static final String TAG = "SaveMe";
    private Camera camera;

    private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;

    Calendar calendar = Calendar.getInstance();
    final int hours = calendar.get(Calendar.HOUR_OF_DAY);
    final int minutes = calendar.get(Calendar.MINUTE);
    int seconds = calendar.get(Calendar.SECOND);


    Date dateNow = new Date();
    SimpleDateFormat dateformatJava = new SimpleDateFormat("dd-MM-yyyy");
    final String date = dateformatJava.format(dateNow);
    private static final String STATE_RESOLVING_ERROR = "resolving_error";
    private static final int REQUEST_RESOLVE_ERROR = 1001;
    private static final String DIALOG_ERROR = "dialog_error";
    private boolean mResolvingError = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        mResolvingError = savedInstanceState != null && savedInstanceState.getBoolean(STATE_RESOLVING_ERROR, false);

        mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addApi(Drive.API)
            .addScope(Drive.SCOPE_FILE)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        recorder = new MediaRecorder();

        initRecorder();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video);



        SurfaceView cameraView = (SurfaceView) findViewById(R.id.CameraView);
        holder = cameraView.getHolder();
        holder.addCallback(this);
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_video, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private void initRecorder() {

        File folder = new File(Environment.getExternalStorageDirectory() + "/SaveMe");
        boolean success = true;
        if (!folder.exists()) {
            success = folder.mkdir();
        }

        File folder2 = new File(Environment.getExternalStorageDirectory() + "/SaveMe/" + date);
        boolean success2 = true;
        if (!folder2.exists()) {
            success2 = folder2.mkdir();
        }

        int cameraId = -1;
        int numberOfCameras = Camera.getNumberOfCameras();
        for (int i = 0; i < numberOfCameras; i++) {
            Camera.CameraInfo info = new Camera.CameraInfo();
            Camera.getCameraInfo(i, info);
            if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                Log.d("saveme", "Camera found");
                cameraId = i;
                break;
            }
        }


        recorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
        recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);

        CamcorderProfile cpHigh = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
        recorder.setProfile(cpHigh);

        file = new java.io.File(Environment.getExternalStorageDirectory() + "/SaveMe/" + date + "/Video " + hours + " " + minutes + ".mp4");
        recorder.setOutputFile(Environment.getExternalStorageDirectory() + "/SaveMe/" + date + "/Video " + hours + " " + minutes + ".mp4");
        Log.i(TAG, "saved");
        recorder.setMaxDuration(9000); // 5 seconds
        recorder.setMaxFileSize(5000000); // Approximately 5 megabytes
        Log.i(TAG, "Start counting");

        new Timer().schedule(new TimerTask() {@Override
            public void run() {
                runOnUiThread(new Runnable() {@Override
                    public void run() {
                        Log.i(TAG, "Thread 7 sec");
                        saveFiletoDrive(file);
                    }
                });
            }
        }, 9000);

    }

    private void saveFiletoDrive(final File file) {
        Log.i(TAG, "Saving....");
        Drive.DriveApi.newDriveContents(getGoogleApiClient()).setResultCallback(
        new ResultCallback < DriveApi.DriveContentsResult > () {@Override
            public void onResult(DriveApi.DriveContentsResult result) {
                String mime = "video/mp4";
                if (!result.getStatus().isSuccess()) {
                    Log.i(TAG, "Failed to create new contents.");
                    return;
                }
                Log.i(TAG, "Connection successful, creating new contents...");
                OutputStream outputStream = result.getDriveContents().getOutputStream();

                FileInputStream fis;
                try {
                    fis = new FileInputStream(file.getPath());
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();

                    byte[] buf = new byte[1024];
                    int n;

                    while ((n = fis.read(buf)) != -1)
                    baos.write(buf, 0, n);

                    outputStream.write(baos.toByteArray());
                    baos.flush();

                    outputStream.close();
                    outputStream = null;
                    fis.close();
                    fis = null;

                } catch (FileNotFoundException e) {
                    Log.w(TAG, "FileNotFoundException: " + e.getMessage());
                } catch (IOException e1) {
                    Log.w(TAG, "Unable to write file contents." + e1.getMessage());
                }

                String title = file.getName();
                MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
                    .setMimeType(mime).setTitle(title).build();

                Drive.DriveApi.getRootFolder(getGoogleApiClient())
                    .createFile(getGoogleApiClient(), metadataChangeSet, result.getDriveContents())
                    .setResultCallback(fileCallback);

                Log.i(TAG, "Creating new video on Drive (" + title + ")");

            }

        });
    }

    final public ResultCallback < DriveFolder.DriveFileResult > fileCallback = new
    ResultCallback < DriveFolder.DriveFileResult > () {@Override
        public void onResult(DriveFolder.DriveFileResult result) {
            if (!result.getStatus().isSuccess()) {
                Log.i(TAG, "Error while trying to create the file");
                return;
            }
            Log.i(TAG, "Successfull !");

        }
    };

    private void prepareRecorder() {
        recorder.setPreviewDisplay(holder.getSurface());

        try {
            recorder.prepare();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void surfaceCreated(SurfaceHolder holder) {

        File folder = new File(Environment.getExternalStorageDirectory() + "/SaveMe");
        boolean success = true;
        if (!folder.exists()) {
            success = folder.mkdir();
        }

        File folder2 = new File(Environment.getExternalStorageDirectory() + "/SaveMe/" + date);
        boolean success2 = true;
        if (!folder2.exists()) {
            success2 = folder2.mkdir();
        }

        prepareRecorder();
        recorder.start();
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        if (recording) {
            recorder.stop();
            recording = false;
        }
        recorder.release();
    }

    public static GoogleApiClient getGoogleApiClient() {
        return mGoogleApiClient;
    }

    @Override
    public void onConnected(Bundle bundle) {
        Log.w(TAG, "Connected to google ");
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    protected void onStart() {
        super.onStart();
        if (!mResolvingError) { // more about this later
            mGoogleApiClient.connect();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mGoogleApiClient.connect();
    }

    @Override
    protected void onPause() {
        super.onPause();
        recorder.release();
        if (mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();
        }
    }

    @Override
    protected void onStop() {
        recorder.release();
        mGoogleApiClient.disconnect();
        super.onStop();
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Log.w(TAG, "failed to connected to google ");
        if (connectionResult.hasResolution()) {
            try {
                connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
            } catch (IntentSender.SendIntentException e) {
                e.printStackTrace();
            }
        } else {
            Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
        }
    }

    private class MyAsyncTask extends AsyncTask < Void, Void, Void > {@Override
        protected Void doInBackground(Void...params) {
            Log.i(TAG, "exec");
            saveFiletoDrive(file);
            return null;
        }@Override
        protected void onPostExecute(Void result) {
        }
    }
}

0 个答案:

没有答案