How to Build an Android App to Compress Video?
Last Updated :
28 Jan, 2022
Nowadays we see many applications are made to compress videos and other files so that users can save memory as well as maintain the quality of that file. In this article, we are going to see how we can compress videos in the android studio and can make our own video compressing application.
What we are going to build in this article?
Below is a sample video of a video compressor that we are going to build in this article. Note that we are going to implement this project using the Java language.
Step by Step Implementation
Step 1: Create a new project
- Open a new project.
- We will be working on Empty Activity with language as Java. Leave all other options unchanged.
- You can change the name of the project at your convenience.
- There will be two default files named activity_main.xml and MainActivity.java.
If you don’t know how to create a new project in Android Studio then you can refer to How to Create/Start a New Project in Android Studio?
Step 2: Adding required dependencies
Open Gradle Scripts > build.gradle(module). and use the following dependencies in it-
implementation 'com.iceteck.silicompressorr:silicompressor:2.2.4'
implementation 'com.googlecode.mp4parser:isoparser:1.1.22'
Click on sync now to save the changes.
Step 3: Adding required permissions
Open the AndroidManifest.xml file and add the following permissions to it-
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Step 4: Working with xml files
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
android:gravity="center_horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/bt_select"
android:text="Select Video"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clipToPadding="false"
android:fitsSystemWindows="true">
<VideoView
android:layout_width="match_parent"
android:layout_height="180dp"
android:id="@+id/video_view1"
android:visibility="gone"/>
</RelativeLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/TextView1"
android:text="Original Video"
android:textSize="20sp"
android:textStyle="bold"
android:visibility="gone"
android:layout_marginTop="8dp"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clipToPadding="false"
android:fitsSystemWindows="true">
<VideoView
android:layout_width="match_parent"
android:layout_height="180dp"
android:id="@+id/Video_view2"
android:visibility="gone"
android:layout_marginTop="32dp"/>
</RelativeLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/text_view2"
android:text="Compressed Video"
android:textSize="20sp"
android:textStyle="bold"
android:visibility="gone"
android:layout_marginTop="8dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/TextView3"
android:textSize="16sp"
android:visibility="gone"
android:layout_marginTop="4dp"/>
</LinearLayout>
Step 5: Working with java files
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
package com.example.videocompress;
import android.Manifest;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.iceteck.silicompressorr.SiliCompressor;
import java.io.File;
import java.net.URISyntaxException;
public class MainActivity extends AppCompatActivity {
// Initialize variable
Button btSelect;
VideoView videoView1, videoView2;
TextView textView1, textView2, textView3;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Assign variable
btSelect = findViewById(R.id.bt_select);
videoView1 = findViewById(R.id.video_view1);
videoView2 = findViewById(R.id.Video_view2);
textView1 = findViewById(R.id.TextView1);
textView2 = findViewById(R.id.text_view2);
textView3 = findViewById(R.id.TextView3);
btSelect.setOnClickListener(
new View.OnClickListener() {
@Override public void onClick(View v)
{
// check condition
if (ContextCompat.checkSelfPermission(
MainActivity.this,
Manifest.permission
.WRITE_EXTERNAL_STORAGE)
== PackageManager
.PERMISSION_GRANTED) {
// When permission is granted
// Create method
selectVideo();
}
else {
// When permission is not granted
// request permission
ActivityCompat.requestPermissions(
MainActivity.this,
new String[] {
Manifest.permission
.WRITE_EXTERNAL_STORAGE },
1);
}
}
});
}
private void selectVideo()
{
// Initialize intent
Intent intent = new Intent(Intent.ACTION_PICK);
// Set type
intent.setType("video/*");
// set action
intent.setAction(Intent.ACTION_GET_CONTENT);
// Start activity result
startActivityForResult(
Intent.createChooser(intent, "Select Video"),
100);
}
@Override
public void onRequestPermissionsResult(
int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults)
{
super.onRequestPermissionsResult(
requestCode, permissions, grantResults);
// check condition
if (requestCode == 1 && grantResults.length > 0
&& grantResults[0]
== PackageManager.PERMISSION_GRANTED) {
// When permission is granted
// Call method
selectVideo();
}
else {
// When permission is denied
// Display Toast
Toast
.makeText(getApplicationContext(),
"Permission Denied !",
Toast.LENGTH_SHORT)
.show();
}
}
@Override
protected void onActivityResult(int requestCode,
int resultCode,
@Nullable Intent data)
{
super.onActivityResult(requestCode, resultCode,
data);
// Check condition
if (requestCode == 100 && resultCode == RESULT_OK
&& data != null) {
// When result is ok
// Initialize Uri
Uri uri = data.getData();
// Set video uri
videoView1.setVideoURI(uri);
// Initialize file
File file = new File(
Environment.getExternalStorageDirectory()
.getAbsolutePath());
// Create compress video method
new CompressVideo().execute(
"false", uri.toString(), file.getPath());
}
}
private class CompressVideo
extends AsyncTask<String, String, String> {
// Initialize dialog
Dialog dialog;
@Override protected void onPreExecute()
{
super.onPreExecute();
// Display dialog
dialog = ProgressDialog.show(
MainActivity.this, "", "Compressing...");
}
@Override
protected String doInBackground(String... strings)
{
// Initialize video path
String videoPath = null;
try {
// Initialize uri
Uri uri = Uri.parse(strings[1]);
// Compress video
videoPath
= SiliCompressor.with(MainActivity.this)
.compressVideo(uri, strings[2]);
}
catch (URISyntaxException e) {
e.printStackTrace();
}
// Return Video path
return videoPath;
}
@Override protected void onPostExecute(String s)
{
super.onPostExecute(s);
// Dismiss dialog
dialog.dismiss();
// Visible all views
videoView1.setVisibility(View.VISIBLE);
textView1.setVisibility(View.VISIBLE);
videoView2.setVisibility(View.VISIBLE);
textView2.setVisibility(View.VISIBLE);
textView3.setVisibility(View.VISIBLE);
// Initialize file
File file = new File(s);
// Initialize uri
Uri uri = Uri.fromFile(file);
// set video uri
videoView2.setVideoURI(uri);
// start both video
videoView1.start();
videoView2.start();
// Compress video size
float size = file.length() / 1024f;
// Set size on text view
textView3.setText(
String.format("Size : %.2f KB", size));
}
}
}
Here is the final output of our application.
Output:
Similar Reads
Android Architecture Android architecture contains a different number of components to support any Android device's needs. Android software contains an open-source Linux Kernel having a collection of a number of C/C++ libraries which are exposed through application framework services. Among all the components Linux Kern
5 min read
Android Tutorial In this Android Tutorial, we cover both basic and advanced concepts. So whether you are a fresher (graduate) or an experienced candidate with several years of Android Development experience, you can follow this Android tutorial to kick-start your journey in Android app development. Our Android Tutor
15+ min read
Activity Lifecycle in Android with Demo App In Android, an activity is referred to as one screen in an application. It is very similar to a single window of any desktop application. An Android app consists of one or more screens or activities. Each activity goes through various stages or a lifecycle and is managed by activity stacks. So when
9 min read
Introduction to Android Development Android operating system is the largest installed base among various mobile platforms across the globe. Hundreds of millions of mobile devices are powered by Android in more than 190 countries of the world. It conquered around 71% of the global market share by the end of 2021, and this trend is grow
5 min read
Top 50 Android Interview Questions and Answers - SDE I to SDE III A Linux-based open-source OS, Android was created by Andy Rubin and became one of the most popular smartphone operating systems. With 71 percent of the market share worldwide, Android is on top. Because it is on top in the smartphone OS, Android development is always in demand.If you are seeking a j
15+ min read
Android UI Layouts Layouts in Android define the user interface and hold UI controls or widgets that appear on the screen of an application. Every Android application consists of View and ViewGroup elements. Since an application contains multiple activitiesâeach representing a separate screenâevery activity has multip
5 min read
Top 50 Flutter Interview Questions and Answers for 2025 Flutter is an open-source, cross-platform application development framework. It was developed by Google in 2017. It is used to build applications for Android, iOS, Linux, Mac, Windows, and the web. Flutter uses the Dart programming language. It provides a simple, powerful, efficient, and easy-to-und
15+ min read
Components of an Android Application There are some necessary building blocks that an Android application consists of. These loosely coupled components are bound by the application manifest file which contains the description of each component and how they interact. The manifest file also contains the appâs metadata, its hardware confi
3 min read
Android Studio Tutorial It is stated that "If you give me six hours to chop down a tree then I will spend the first four hours in sharpening the axe". So in the Android Development World if we consider Android Development as the tree then Android Studio should be the axe. Yes, if you are starting Android Development then y
9 min read
MVVM (Model View ViewModel) Architecture Pattern in Android Developers always prefer clean and structured code for projects. Organizing the codes according to a design pattern helps in the maintenance of the software. By having knowledge of all crucial logic parts of the android application, it is easier to add and remove app features. Further, design patter
8 min read