Skip to content Skip to sidebar Skip to footer

How To Trim The Video With Start & End Time In Android Programmatically?

I want to trim the local video based on start and end time in android programmatically ,I tried below attached few links but haven't worked for me.Please let me know any working li

Solution 1:

Use FFMPEG library to solve your problem. Thanks for writingminds to make ffmpeg simple for android 1. implementation 'com.writingminds:FFmpegAndroid:0.3.2'

  1. initialize ffmpeg

    privatevoidsetUpFFmpeg() {
    ffmpeg = FFmpeg.getInstance(context);
    
    
    try {
        ffmpeg.loadBinary(newLoadBinaryResponseHandler() {
    
            @OverridepublicvoidonStart() {
                Log.d("Event ", "onStart");
            }
    
            @OverridepublicvoidonFailure() {
                Log.d("Event ", "onFailure");
            }
    
            @OverridepublicvoidonSuccess() {
                Log.d("Event ", "onSuccess");
            }
    
            @OverridepublicvoidonFinish() {
                Log.d("Event ", "onFinish");
    
            }
        });
    } catch (FFmpegNotSupportedException e) {
        // Handle if FFmpeg is not supported by device
    }
    }
    
  2. use FFMPEG command like @Mahesh Keshvala posted above. Good work @Mahesh

  3. then execFFmpegBinary(complexCommand); will be like this

    privatevoidexecFFmpegBinary(String[] command){
          try {
    
        ffmpeg.execute(commands, newExecuteBinaryResponseHandler() {
    
            @OverridepublicvoidonStart() {
                Log.d("Event ", "onStart");
            }
    
            @OverridepublicvoidonProgress(String message) {
                Log.e("Event ", "onProgress - " + message);
    
            }
    
            @OverridepublicvoidonFailure(String message) {
                Log.e("Event ", "onFailure - " + message);
    
            }
    
            @OverridepublicvoidonSuccess(String message) {
                Log.e("Event ", "onSuccess - " + message);
    
            }
    
            @OverridepublicvoidonFinish() {
                Log.e("Event ", "onFinish");
    
            }
        });
    } catch (FFmpegCommandAlreadyRunningException e) {
        // Handle if FFmpeg is already running
     }
    }
    

try command for cut video

String[] complexCommand = {"-ss", "" + startMs / 1000, "-y", "-i", inputFileAbsolutePath, "-t", "" + (endMs - startMs) / 1000, "-s", "320x240", "-r", "15", "-vcodec", "mpeg4", "-b:v", "2097152", "-b:a", "48000", "-ac", "2", "-ar", "22050", outputFileAbsolutePath};

to know more about ffmpeg android refer this link

Solution 2:

Here is the solution using FFMPEG library use below function to trim or cut the video, may this will work for you:

privatevoidexecuteCutVideoCommand(int startMs, int endMs) {
    File moviesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES
    );

    String filePrefix = "cut_video";
    String fileExtn = ".mp4";
    String yourRealPath = getPath(VideoEffectActivity.this, selectedVideoUri);
    File dest = newFile(moviesDir, filePrefix + fileExtn);
    int fileNo = 0;
    while (dest.exists()) {
        fileNo++;
        dest = newFile(moviesDir, filePrefix + fileNo + fileExtn);
    }

    Log.d(TAG, "startTrim: src: " + yourRealPath);
    Log.d(TAG, "startTrim: dest: " + dest.getAbsolutePath());
    Log.d(TAG, "startTrim: startMs: " + startMs);
    Log.d(TAG, "startTrim: endMs: " + endMs);
    filePath = dest.getAbsolutePath();
    //String[] complexCommand = {"-i", yourRealPath, "-ss", "" + startMs / 1000, "-t", "" + endMs / 1000, dest.getAbsolutePath()};String[] complexCommand = {"-ss", "" + startMs / 1000, "-y", "-i", yourRealPath, "-t", "" + (endMs - startMs) / 1000, "-vcodec", "mpeg4", "-b:v", "2097152", "-b:a", "48000", "-ac", "2", "-ar", "22050", filePath};

    execFFmpegBinary(complexCommand);

}


 privatevoidexecFFmpegBinary(final String[] command) {
    try {
        ffmpeg.execute(command, newExecuteBinaryResponseHandler() {
            @OverridepublicvoidonFailure(String s) {
                Log.d(TAG, "FAILED with output : " + s);
            }

            @OverridepublicvoidonSuccess(String s) {
                Log.d(TAG, "SUCCESS with output : " + s);
               //You have to create a class of Preview Activity//If you don't have please remove below Intent codeIntent intent = newIntent(VideoEffectActivity.this, PreviewActivity.class);
                    intent.putExtra(FILEPATH, filePath);
                    startActivity(intent);
            }

            @OverridepublicvoidonProgress(String s) {
                    progressDialog.setMessage("progress : " + s);
                Log.d(TAG, "progress : " + s);
            }

            @OverridepublicvoidonStart() {
                Log.d(TAG, "Started command : ffmpeg " + command);
                progressDialog.setMessage("Processing...");
                progressDialog.show();
            }

            @OverridepublicvoidonFinish() {
                Log.d(TAG, "Finished command : ffmpeg " + command);
               progressDialog.dismiss();
            }
        });
    } catch (FFmpegCommandAlreadyRunningException e) {
        // do nothing for now
    }
}

Put this dependency into gradle file:

compile'com.writingminds:FFmpegAndroid:0.3.2'

Solution 3:

Updated solution ffmpeg library in Kotlin. This solution is tested with SDK Versions 21 to 30.

First, you need to add the dependency

implementation 'com.arthenica:mobile-ffmpeg-full:4.2.2.LTS'

Below, is the code snippet for trimming the video.

Note: You need to run the below code inside the background thread by using AsyncTask or Kotlin Coroutines

val outputFile = UtilsFile.createVideoFile(context)
        val command =
            arrayOf(
                "-ss",
                "1",    //Start point in seconds"-y",
                "-i",
                inputFile.absolutePath,
                "-t",
                "60",   //Ending point in seconds"-s",
                "648x1152",
                "-r",
                "15",
                "-vcodec",
                "mpeg4",
                "-b:v",
                "2097152",
                "-b:a",
                "48000",
                "-ac",
                "2",
                "-ar",
                "22050",
                outputFile.absolutePath
            )
        val rc = FFmpeg.execute(command)

        if (rc == RETURN_CODE_SUCCESS) {
            Log.i(TAG, "Command execution completed successfully.")
            return outputFile
        } elseif (rc == RETURN_CODE_CANCEL) {
            Log.i(TAG, "Command execution cancelled by user.")
        } else {
            Log.i(
                TAG,
                String.format(
                    "Command execution failed with rc=%d and the output below.",
                    rc
                )
            )
        }

Post a Comment for "How To Trim The Video With Start & End Time In Android Programmatically?"