6

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 libraries or sample code to overcome this?

Refereed links:

  1. Android sdk cut/trim video file
  2. How to trim the video using FFMPEG library in android?
  3. https://superuser.com/questions/377343/cut-part-from-video-file-from-start-position-to-end-position-with-ffmpeg

Thanks in advance!

Bagus Cahyono
  • 668
  • 2
  • 8
  • 17

3 Answers3

5

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

    private void setUpFFmpeg() {
    ffmpeg = FFmpeg.getInstance(context);
    
    
    try {
        ffmpeg.loadBinary(new LoadBinaryResponseHandler() {
    
            @Override
            public void onStart() {
                Log.d("Event ", "onStart");
            }
    
            @Override
            public void onFailure() {
                Log.d("Event ", "onFailure");
            }
    
            @Override
            public void onSuccess() {
                Log.d("Event ", "onSuccess");
            }
    
            @Override
            public void onFinish() {
                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

    private void execFFmpegBinary(String[] command){
          try {
    
        ffmpeg.execute(commands, new ExecuteBinaryResponseHandler() {
    
            @Override
            public void onStart() {
                Log.d("Event ", "onStart");
            }
    
            @Override
            public void onProgress(String message) {
                Log.e("Event ", "onProgress - " + message);
    
            }
    
            @Override
            public void onFailure(String message) {
                Log.e("Event ", "onFailure - " + message);
    
            }
    
            @Override
            public void onSuccess(String message) {
                Log.e("Event ", "onSuccess - " + message);
    
            }
    
            @Override
            public void onFinish() {
                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

Sam Raju
  • 189
  • 8
  • Showing below error while executing execFFmpegBinary block. Error: E/FFmpeg: Exception while trying to run: [Ljava.lang.String;@dbe0367 java.io.IOException: Error running exec(). Command: [/data/user/0/com.psp.testvideotrim/files/ffmpeg, -ss, 0, -y, -i, /storage/emulated/0/test/Media/test Video/VID-20180522-WA0008.mp4, -t, 3, -vcodec, mpeg4, -b:v, 2097152, -b:a, 48000, -ac, 2, -ar, 22050, /storage/emulated/0/Movies/cut_video.mp4] Working Directory: null Environment: null – Srinivasa Prudhvi Pendem May 24 '18 at 05:50
  • 05-24 11:10:52.474 19740-19740/com.psp.testvideotrim E/Event: onFailure - 05-24 11:10:52.475 19740-19740/com.psp.testvideotrim E/Event: onFinish – Srinivasa Prudhvi Pendem May 24 '18 at 05:51
  • i update my answer please check that, also refer that [link](https://androidlearnersite.wordpress.com/2017/03/17/ffmpeg-video-editor/) too. I use the same method in one of my project – Sam Raju May 24 '18 at 08:12
  • this is not working on android 10.you can use this library https://github.com/a914-gowtham/Android-video-trimmer – gowtham6672 Jul 22 '20 at 15:32
  • @gowtham6672 Link is broken i think library is not maintained anymore. – Rahul Bh Aug 08 '20 at 11:39
  • check that link now @RahulChaudhary – gowtham6672 Aug 11 '20 at 14:07
  • This answer will not work for SDK level greater than 9. You can check my updated answer below https://stackoverflow.com/questions/50501049/how-to-trim-the-video-with-start-end-time-in-android-programmatically/65741422#65741422 – Hantash Nadeem Jan 15 '21 at 18:13
1

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

private void executeCutVideoCommand(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 = new File(moviesDir, filePrefix + fileExtn);
    int fileNo = 0;
    while (dest.exists()) {
        fileNo++;
        dest = new File(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);

}


 private void execFFmpegBinary(final String[] command) {
    try {
        ffmpeg.execute(command, new ExecuteBinaryResponseHandler() {
            @Override
            public void onFailure(String s) {
                Log.d(TAG, "FAILED with output : " + s);
            }

            @Override
            public void onSuccess(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 code
                    Intent intent = new Intent(VideoEffectActivity.this, PreviewActivity.class);
                    intent.putExtra(FILEPATH, filePath);
                    startActivity(intent);
            }

            @Override
            public void onProgress(String s) {
                    progressDialog.setMessage("progress : " + s);
                Log.d(TAG, "progress : " + s);
            }

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

            @Override
            public void onFinish() {
                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'
Mahesh Keshvala
  • 1,349
  • 12
  • 19
  • "execFFmpegBinary(complexCommand);" Showing error even integrating the above library? – Srinivasa Prudhvi Pendem May 24 '18 at 05:26
  • Unable to create "execFFmpegBinary(complexCommand);" Below " Sam Raju " answer helped me to create that. – Srinivasa Prudhvi Pendem May 24 '18 at 05:37
  • Showing below error while executing execFFmpegBinary block. Error: E/FFmpeg: Exception while trying to run: [Ljava.lang.String;@a1d6f03 java.io.IOException: Error running exec(). Command: [/data/user/0/com.psp.testvideotrim/files/ffmpeg, -i, /storage/emulated/0/WhatsApp Business/Media/WhatsApp Business Video/VID-20180522-WA0000.mp4, -ss, 0, -t, 30, /storage/emulated/0/Movies/cut_video.mp4] Working Directory: null Environment: null – Srinivasa Prudhvi Pendem May 24 '18 at 06:17
  • please check all the conditions you put like permission read,write and access of storage and all that may be because of that you get this error. – Mahesh Keshvala May 24 '18 at 06:18
  • I have given all permissions too...But Error still persists@mahes Keshavala – Srinivasa Prudhvi Pendem May 24 '18 at 07:03
  • use this library https://github.com/a914-gowtham/Android-video-trimmer – gowtham6672 Jul 22 '20 at 15:32
0

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
        } else if (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
                )
            )
        }
Hantash Nadeem
  • 458
  • 6
  • 10