Capture a video and store it at a specific location rather than a default location

后端 未结 3 1924
长发绾君心
长发绾君心 2021-01-03 14:07

I want to capture video and store video at specific location other than default location.

I know there is a method with MediaStore called setOutPutFile(\"Strin

3条回答
  •  心在旅途
    2021-01-03 14:15

    The answer given by abhi here is correct, but i am writing a new answer to make it more easy and simple to other users.

    To record a video, write this code in your onCreate method or on button click where you want to start the video recording

    private static final int ACTION_TAKE_VIDEO = 3;
    
    Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
    startActivityForResult(takeVideoIntent, ACTION_TAKE_VIDEO);
    

    This code will start video recording.

    Now below in your code after the onCreate method you need to override a method which name is onActivityResult.

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    
        if (resultCode == RESULT_OK) 
        {
            try
            {
                AssetFileDescriptor videoAsset = getContentResolver().openAssetFileDescriptor(data.getData(), "r");
                FileInputStream fis = videoAsset.createInputStream();
                File root=new File(Environment.getExternalStorageDirectory(),"/RecordVideo/");  //you can replace RecordVideo by the specific folder where you want to save the video
                if (!root.exists()) {
                    System.out.println("No directory");
                    root.mkdirs();
                }
    
                File file;
                file=new File(root,"android_"+System.currentTimeMillis()+".mp4" );
    
                FileOutputStream fos = new FileOutputStream(file);
    
                byte[] buf = new byte[1024];
                int len;
                while ((len = fis.read(buf)) > 0) {
                    fos.write(buf, 0, len);
                }       
                fis.close();
                fos.close();
            } 
            catch (Exception e) 
            {
                e.printStackTrace();
            }
        }
    }
    

    Replace "RecordVideo" with the specific folder where you want to the video file on your sd card. You can also use any existing folder or directory name here.

    Thanks

提交回复
热议问题