Record, save and play a video in Android

前端 未结 3 757
南方客
南方客 2021-02-06 09:36

I am trying to make an app that records a video using the camera app, and then saves that video on SD card so I can play it. I have some code but I\'m lost on how to continue as

3条回答
  •  再見小時候
    2021-02-06 09:55

        // Put this code in ,on Button click or in onCreate to Capture the Video 
    
    
      Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        videoUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, videoUri);
        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
        startActivityForResult(intent, CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);
    
      ////////////////////////////////
    
    
    private static Uri getOutputMediaFileUri(int type){
        return Uri.fromFile(getOutputMediaFile(type));
    }
    
    private static File getOutputMediaFile(int type){
        // Check that the SDCard is mounted
        File mediaStorageDir = new File(Environment.getExternalStorageDirectory() +"/YourDirectoryName");
        // Create the storage directory(MyCameraVideo) if it does not exist
        if (! mediaStorageDir.exists()){
    
            if (! mediaStorageDir.mkdirs()){
    
                Log.d("MyCameraVideo", "Failed to create directory MyCameraVideo.");
                return null;
            }
        }
    
        // Create a media file name
        // For unique file name appending current timeStamp with file name
        java.util.Date date= new java.util.Date();
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(date.getTime());
    
        File mediaFile;
        if(type == MEDIA_TYPE_VIDEO) {
    
            // For unique video file name appending current timeStamp with file name
            mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                    "VID_"+ timeStamp + ".mp4");
    
        } else {
            return null;
        }
    
        return mediaFile;
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // After camera screen this code will execute
        if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE ) {
    
            if (resultCode == RESULT_OK) {
                videoUri = data.getData();
    
                // Video captured and saved to fileUri specified in the Intent
              //  Toast.makeText(getActivity(), "Video saved to: " +data.getData(), Toast.LENGTH_LONG).show();
    
            } else if (resultCode == RESULT_CANCELED) {
    
                // User cancelled the video capture
                Toast.makeText(getActivity(), "User cancelled the video capture.", Toast.LENGTH_LONG).show();
    
            } else {
               // Video capture failed, advise user
                Toast.makeText(getActivity(), "Video capture failed.", Toast.LENGTH_LONG).show();
            }
        }
    }
    

提交回复
热议问题