Android Studio

How to compress video in android studio without effecting quality android studio 2019 coder vlog

video compression android studio
video compression android studio

In this post, you will learn how to compress video in android studio. There are many ways to compress video in android. The logic used for compressing video is use low bit rate for video and convert video to lower resolution helps you to lower the file size of video but you have to also care about quality of video, that must be less effect  during video compression. There is one way to compress video with no quality compromise and that is zipping the video, that reduce file size and increase speed of upload video but for larger size video it will be not effective, but for small size video it is very good choice. There are many libraries for video compressing without doing it zip that are


1. FFmpeg 4 android
2. Silicompressor
3. Giraffe Compressor
4. isoparser-1.0.6.jar and aspectjrt-1.7.3.jar (contain buildin function to help you compress video).

Download Demo of this app from play store

https://play.google.com/store/apps/details?id=com.saifyproduction.videocompressing


My favorite library is FFmpeg because it is so accurate and it did not effect your video quality and also give you more control (programming related) but it is little tricky to implement. For this tutorial i will be using isoparser-1.0.6.jar and aspectjrt-1.7.3.jar, it will be simple for you, just copy videocompressor project and paste in your project and use three line of code to compress video, no coding stress for you. First add these two permission in your manifest file


<uses permission android:name=”android.permission.WRITE_EXTERNAL_STORAGE”/>

<uses-permission android:name=”android.permission.READ_EXTERNAL_STORAGE”/>

You need to download this project (link is below) and paste it in your project. See the picture to understand.

https://github.com/fishwjy/VideoCompressor

compress video in android studio
compress video in android studio
compress video in android studio
compress video in android studio

Create these classes in your project.


VideoCompressAsyncTask.java

In this class, I am compressing video using Async task, Async task is good way to run operation in background along with GUI of android.

import android.content.Context;
import android.media.MediaRecorder;
import android.os.AsyncTask;
import android.widget.MediaController;
import android.widget.Toast;

import com.vincent.videocompressor.VideoCompress;

import java.io.File;
import java.util.HashMap;

public class VideoCompressAsyncTask extends AsyncTask<String, String, String> {

    VideoCompress.CompressListener lis ;
    Context mContext;
    int dis = 0;

    public VideoCompressAsyncTask(Context context ){
        mContext = context;
    }

    @Override
    protected void onPreExecute() {
       super.onPreExecute();
    }


    @Override
    protected String doInBackground(final String... paths) {

        try {

           VideoCompress.compressVideoMedium(paths[0], paths[1], lis = new VideoCompress.CompressListener() {

             @Override
                public void onStart() {

                }

                @Override
                public void onSuccess() {


                    if (dis == 0) {

                        SharedPrefUtil.getInstance(mContext).putString("1", "1");
                        MainActivity.showfile();


                    } else {

                        File n = new File(paths[1]);
                        if (n.exists()) {
                            n.delete();
                        }
                    }
                }

                @Override
                public void onFail() {

                    Toast.makeText(mContext, "Failed to compress :", Toast.LENGTH_SHORT).show();

                }

                @Override
                public void onProgress(float percent) {

                    int p = (int) percent;
                    String st = SharedPrefUtil.getInstance(mContext).getString("stop");
                    if (dis == 0) {
                        if (st.equalsIgnoreCase("1")) {

                            dis = 1;
                        } else {

                            MainActivity.updatepro(p);

                        }

                    }

                }


            });

        }catch (Exception e){
            System.out.println("Error = "+e.getMessage().toString());

        }

        return null;
    }

    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);

    }

    @Override
    protected void onPostExecute(String compressedFilePath) {
        super.onPostExecute(compressedFilePath);

    }

}

SharedPrefUtil.java


In this class, I am storing some values and retrieving it for check status of compressing video and avoid multiple video compression at time (one compression at a time)

import android.content.Context;
import android.content.SharedPreferences;


public class SharedPrefUtil {

    private static final String SHARED_APP_PREFERENCE_NAME = "SharedPref";
    Context cxt;
    private SharedPreferences pref;
    private SharedPreferences.Editor mEditor;

    public SharedPrefUtil(Context context) {
        this.pref = context.getSharedPreferences(SHARED_APP_PREFERENCE_NAME, Context.MODE_PRIVATE);
    }

    public static SharedPrefUtil getInstance(Context context) {
        return new SharedPrefUtil(context);
    }

    public void putString(String key, String value) {
        pref.edit().putString(key, value).apply();
    }

    public void putInteger(String key, int value) {
        pref.edit().putInt(key, value).apply();
    }

    public void putBoolean(String key, boolean value) {
        pref.edit().putBoolean(key, value).apply();
    }

    public String getString(String key)
    {
        return pref.getString(key,"");
    }

    public int getInteger(String key)
    {
        return pref.getInt(key,0);
    }

    public boolean getBoolean(String key)
    {
        return pref.getBoolean(key,false);
    }

}

MainActivity.java
It is activity in which you compress videos. 

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;

public class MainActivity extends AppCompatActivity {


    int f = 0;

    static Button add;
    static TextView per , view;


    static public void updatepro(int n){

        per.setText(n+" %");

    }


    static public void showfile(){


        per.setVisibility(View.GONE);
        view.setVisibility(View.VISIBLE);
        add.setText("Add Video");



    }



    @Override
    protected void onResume() {
        super.onResume();

        String m = SharedPrefUtil.getInstance(MainActivity.this).getString("1");

        if(m!=null){

            if(m.equalsIgnoreCase("0")){

                per.setVisibility(View.VISIBLE);

            }
            else{

                per.setVisibility(View.GONE);
                view.setVisibility(View.GONE);

            }

        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        add = (Button) findViewById(R.id.add_video);
        per = (TextView) findViewById(R.id.per);
        view = (TextView) findViewById(R.id.view_file);

        per.setVisibility(View.GONE);
        view.setVisibility(View.GONE);


        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                File yourFile = new File(Environment.getExternalStorageDirectory().toString()+"/n1.mp4");
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                String type = "video/*";


                Uri uri;
                if (Build.VERSION.SDK_INT < 24) {
                    uri = Uri.fromFile(yourFile);
                } else {
                    uri = Uri.parse(yourFile.getPath()); // My work-around for new SDKs, causes ActivityNotFoundException in API 10.
                }


                intent.setDataAndType(uri, type);

                startActivity(intent);

            }
        });

        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ) {


                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE },1);
                    }

                }
                else {


                    String s = SharedPrefUtil.getInstance(MainActivity.this).getString("1");
                    if (s.isEmpty()) {
                        SharedPrefUtil.getInstance(MainActivity.this).putString("1", "0");
                        SharedPrefUtil.getInstance(MainActivity.this).putString("stop", "0");

                        Intent pickIntent = new Intent(Intent.ACTION_PICK);
                        pickIntent.setType("video/*");
                        startActivityForResult(pickIntent, 1);

                    } else {

                        if (s.equalsIgnoreCase("1")) {
                            SharedPrefUtil.getInstance(MainActivity.this).putString("1", "0");
                            SharedPrefUtil.getInstance(MainActivity.this).putString("stop", "0");

                            Intent pickIntent = new Intent(Intent.ACTION_PICK);
                            pickIntent.setType("video/*");
                            startActivityForResult(pickIntent, 1);


                        } else {
                            // Stop

                            SharedPrefUtil.getInstance(MainActivity.this).putString("stop", "1");
                            per.setVisibility(View.GONE);
                            view.setVisibility(View.GONE);
                            SharedPrefUtil.getInstance(MainActivity.this).putString("1", "1");

                            add.setText("Add Video");

                        }


                    }

                }
            }
        });

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if ( resultCode==RESULT_OK && data !=null && data.getData() !=null || requestCode == 1) {

            String state = Environment.getExternalStorageState();
            if (!Environment.MEDIA_MOUNTED.equals(state)) {
                // Can read and write the media
                Toast.makeText(MainActivity.this, "Sorry some problem to phone storage ", Toast.LENGTH_SHORT).show();
                return;
            }

            String  local_address = Environment.getExternalStorageDirectory().toString()+"/n1.mp4";
            File ff = new File(local_address);

            if(ff.exists()){
                ff.delete();
            }

            VideoCompressAsyncTask videocompress = new VideoCompressAsyncTask(this);
            videocompress.execute(  getVideopath(data.getData(), MainActivity.this),  local_address  );
            per.setVisibility(View.VISIBLE);
            per.setText("0%");
            add.setText("Stop Compressing");


        }
        else {

            SharedPrefUtil.getInstance(MainActivity.this).putString("stop","1");
            per.setVisibility(View.GONE);
            view.setVisibility(View.GONE);
            SharedPrefUtil.getInstance(MainActivity.this).putString("1","1");
            add.setText("Add Video");
        }

    }

    public  String getVideopath(Uri uri , Context cnt ) {
        String[] filePathColumn = {MediaStore.Video.Media.DATA};
        Cursor cursor = cnt.getContentResolver().query(uri, filePathColumn, null, null, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();
        return picturePath;
    }

}