How to trim the video programatically in android?

  • Replies:21
rajesh s
  • Forum posts: 12

Nov 21, 2014, 8:19:17 AM via Website

I am new to the android development.In my project 10sec video uploading the amazon server.so,my video trim in 10 sec or less.I was done lot of research but i didn't get any solution.please tell me anyone known.It is most important for me.Adavance thanks to all.

Marlon Brandomon

Reply
Kevin Berendsen
  • Forum posts: 118

Nov 21, 2014, 12:35:52 PM via Website

It doesn't really come with the standard Android SDK as far as I know.

Take a look over here: https://software.intel.com/en-us/articles/intel-inde-media-pack-for-android-tutorials-running-samples

It has a sample of cutting a video which you can use in your application by downloading and including their Starter Edition pack. It's completely free but you'd have to register through and can be used in Android Studio, Eclipse and many other IDEs.

Open source example codes that includes the java files to trim/cut your video into segments. You can even compress the videos which can be done by standard Android SDK as well.

https://github.com/INDExOS/media-for-mobile/tree/master/Android/samples/apps/src/com/intel/inde/mp/samples

Click here to register for Intel INDE.

I hope this helps you in the right direction :)

Marlon Brandomon

Reply
rajesh s
  • Forum posts: 12

Nov 24, 2014, 12:49:54 PM via Website

Hi, Thanks for your information. I tried this sample but i facing the one problem.After trimming the portrait video orientation is changed to landscape.

portrait video is changed to landscape mode after trimming?please help me for this

Reply
Kevin Berendsen
  • Forum posts: 118

Nov 24, 2014, 1:11:30 PM via Website

Does the video change it's mode or your smartphone view?

Reply
rajesh s
  • Forum posts: 12

Nov 24, 2014, 1:16:10 PM via Website

Hi,

After trimming portrait video is changed to landscape.i don't know video mode is changed or not but view is changed to landscape mode.

Reply
Kevin Berendsen
  • Forum posts: 118

Nov 24, 2014, 1:25:20 PM via Website

Could you post your code that does the trimming? (the activity/fragment plus everything else that is involved in the trimming activity/fragment) I have a slight idea where the issue forms.

— modified on Nov 24, 2014, 1:25:52 PM

Reply
rajesh s
  • Forum posts: 12

Nov 24, 2014, 1:32:52 PM via Website

I am not writing any code using intel inde,i am just checking your given sample.Before that i am using Mp4 parser for trimming,same issue in mp4 parser also.code is given below(MP4 parser code)

private void trimVideo(float start, float end) 
    {
        // TODO Auto-generated method stub
         try 
         {

            Log.e("vidpath before triming","viddeo path before triming<><><><ashok"+strImagePath);
            File folder = Ut.getTestMp4ParserVideosDir(this);
            Movie movie = MovieCreator.build(new FileInputStream(new File(strImagePath)).getChannel());
            List<Track> tracks = movie.getTracks();
            movie.setTracks(new LinkedList<Track>());
            // remove all tracks we will create new tracks from the old

            Log.e("No. of tracks==","<>"+tracks.size()+" Start="+start);
            double startTime = start;//0;
            double endTime =(double) getDuration(tracks.get(0)) / tracks.get(0).getTrackMetaData().getTimescale();
            endTime= Math.min(endTime, end);
            Log.e("endTime","<>"+endTime);
            boolean timeCorrected = false;

            // Here we try to find a track that has sync samples. Since we can only start decoding
            // at such a sample we SHOULD make sure that the start of the new fragment is exactly
            // such a frame
            for (Track track : tracks) 
            {
                if (track.getSyncSamples() != null && track.getSyncSamples().length > 0) 
                {
                    if (timeCorrected) 
                    {
                        // This exception here could be a false positive in case we have multiple tracks
                        // with sync samples at exactly the same positions. E.g. a single movie containing
                        // multiple qualities of the same video (Microsoft Smooth Streaming file)

                        throw new RuntimeException("The startTime has already been corrected by another track with SyncSample. Not Supported.");
                    }
                    startTime = correctTimeToSyncSample(track, startTime, false);
                    endTime = correctTimeToSyncSample(track, endTime, true);
                    timeCorrected = true;
                }
            }

            for (Track track : tracks) 
            {
                long currentSample = 0;
                double currentTime = 0;
                long startSample = -1;
                long endSample = -1;

                for (int i = 0; i < track.getDecodingTimeEntries().size(); i++) 
                {
                    TimeToSampleBox.Entry entry = track.getDecodingTimeEntries().get(i);
                    for (int j = 0; j < entry.getCount(); j++) 
                    {
                        // entry.getDelta() is the amount of time the current sample covers.

                        if (currentTime <= startTime) 
                        {
                            // current sample is still before the new starttime
                            startSample = currentSample;
                        }else  if (currentTime <= endTime) 
                        {
                            // current sample is after the new start time and still before the new endtime
                            endSample = currentSample;
                        } else 
                        {
                            // current sample is after the end of the cropped video
                            break;
                        }
                        currentTime += (double) entry.getDelta() / (double) track.getTrackMetaData().getTimescale();
                        currentSample++;
                    }
                }
                Log.e("<>=","startSample="+startSample+" endSample"+endSample);
                movie.addTrack(new CroppedTrack(track, startSample, endSample));


                Log.e("<><>>","<><><");
            }
            long start1 = System.currentTimeMillis();
            IsoFile out = new DefaultMp4Builder().build(movie);
            long start2 = System.currentTimeMillis();

            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            filename1 = folder.getPath() + File.separator + String.format("Trimming", startTime, endTime) + "_" + timeStamp + ".mp4";
            FileOutputStream fos = new FileOutputStream(filename1);
            Log.e("after trim","after trim ing videopath ashok<><><><><><><"+filename1.toString());
            FileChannel fc = fos.getChannel();
            out.getBox(fc);
            fc.close();
            fos.close();
            long start3 = System.currentTimeMillis();
            System.err.println("Building IsoFile took : " + (start2 - start1) + "ms");
            System.err.println("Writing IsoFile took  : " + (start3 - start2) + "ms");
            System.err.println("Writing IsoFile speed : " + (new File(String.format("TMP4_APP_OUT-%f-%f", startTime, endTime)).length() / (start3 - start2) / 1000) + "MB/s");

            CreatingThumb1(filename1);

         } 
         catch (FileNotFoundException e) 
         {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
         catch (IOException e) 
         {
            // TODO Auto-generated catch block
            e.printStackTrace();
         }
    } 

    protected static long getDuration(Track track) 
    {
        long duration = 0;
        for (TimeToSampleBox.Entry entry : track.getDecodingTimeEntries()) 
        {
            duration += entry.getCount() * entry.getDelta();
        }
        return duration;
    }

    private static double correctTimeToSyncSample(Track track, double cutHere, boolean next) 
    {
        double[] timeOfSyncSamples = new double[track.getSyncSamples().length];
        long currentSample = 0;
        double currentTime = 0;
        for (int i = 0; i < track.getDecodingTimeEntries().size(); i++) 
        {
            TimeToSampleBox.Entry entry = track.getDecodingTimeEntries().get(i);
            for (int j = 0; j < entry.getCount(); j++) {
                if (Arrays.binarySearch(track.getSyncSamples(), currentSample + 1) >= 0)
                {
                    // samples always start with 1 but we start with zero therefore +1
                    timeOfSyncSamples[Arrays.binarySearch(track.getSyncSamples(), currentSample + 1)] = currentTime;
                }
                currentTime += (double) entry.getDelta() / (double) track.getTrackMetaData().getTimescale();
                currentSample++;
            }
        }
        double previous = 0;
        for (double timeOfSyncSample : timeOfSyncSamples) 
        {
            if (timeOfSyncSample > cutHere)
            {
                if (next) 
                {
                    return timeOfSyncSample;
                }
                else 
                {
                    return previous;
                }
            }
            previous = timeOfSyncSample;
        }
        return timeOfSyncSamples[timeOfSyncSamples.length - 1];
    }

Reply
Kevin Berendsen
  • Forum posts: 118

Nov 24, 2014, 1:49:56 PM via Website

Could you post your XML layout file? That contains the VideoView element and your android manifest. Make sure you mark/remove personal details or api keys which are in your android manifest :)

Your provided code contains nothing that force changes your smartphone's orientation.

— modified on Nov 24, 2014, 1:50:22 PM

Reply
rajesh s
  • Forum posts: 12

Nov 24, 2014, 2:02:55 PM via Website

please give me your mail id,xml files are showing the error in this forum so i can't post the xml files

Reply
Kevin Berendsen
  • Forum posts: 118

Nov 24, 2014, 2:11:33 PM via Website

I sent you a private message with my email adres, check your inbox :)

Reply
Kevin Berendsen
  • Forum posts: 118

Nov 24, 2014, 2:57:41 PM via Website

Kevin Berendsen

I sent you a private message with my email adres, check your inbox :)

Thanks for your reply with the requested files.

What's the activity's name where you trim the video because there are only two activities mentioned in your Android Manifest.

Reply
rajesh s
  • Forum posts: 12

Nov 24, 2014, 3:03:04 PM via Website

my activity name is Camera activity and first method for trimming

ajazgames

Reply
Kevin Berendsen
  • Forum posts: 118

Nov 24, 2014, 3:09:28 PM via Website

rajesh s

my activity name is Camera activity and first method for trimming

Ah great, remove android:screenOrientation="portrait" of CameraActivity in your manifest. You're trying to force portrait orientation. Reply back with what happens. If the problem still exists, make a screenshot right before you trim to the video and after you trimmed the video to give me a better idea of what's happening.

ajazgames

Reply
Sritam Jagadev
  • Forum posts: 1

Dec 19, 2014, 10:53:26 AM via Website

can you please send me this application source code in jagadevsritam@gmail.com

ajazgames

Reply
rajesh s
  • Forum posts: 12

Dec 19, 2014, 11:52:15 AM via Website

i am using Mp4 Parser for trimming but it is not working.....

ajazgames

Reply
Virani Ashish
  • Forum posts: 1

Nov 30, 2016, 12:15:46 PM via Website

using this lib to trim your video easy
video-trimmer on github

ajazgames

Reply
Najaf Ali
  • Forum posts: 1

Jun 17, 2017, 10:16:41 AM via Website

today its become trend to Download videos and then trim them normally so you can easily do this by using:
1. Downlaod video first .

2.trim video using this app:

Reply
Yi Jung
  • Forum posts: 1

Jul 16, 2018, 8:36:22 AM via Website

I would like to see your XML layout file as well that includes VideoView element and android manifest
this is my mail svd99617@gmail.com

Reply
Stephanie
  • Forum posts: 9

Jul 17, 2018, 5:33:35 AM via Website

Why not do this on the computer? I think it is inconvenient to edit videos on a phone because the screen is too small. Besides, the video definition may not so high when played on PC. Well, it is just my opinion. :P

Reply
Stephanie
  • Forum posts: 9

Aug 6, 2018, 8:45:50 AM via Website

Thanks for your advice, it's useful.

Reply
Tushaar Kamat
  • Forum posts: 12

Aug 14, 2018, 1:59:41 AM via Website

Same, this helped

Reply
Chatmoresley
  • Forum posts: 15

Mar 5, 2021, 11:25:46 AM via Website

I have tried many Android apps to trim videos, but none of them satisfy me. Now I'm using a desktop tool called Joyoshare VidiKit. It is able to cut and trim videos and audios losslessly. Moreover, it has many other features to edit and personalize video files. I like it.

Reply