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
How to Compress a Video On Android?
Videos are an important way to share thoughts among people. Videos are a combination of audio & visuals. So, it helps a lot to share the proper thoughts with the community. So, nowadays, users are often interested to create new videos. That may be a reel video. Or sometimes it may be a motivatio
4 min read
How to Build a Simple e-Crackers App using Android?
Pre-requisites: Android App Development Fundamentals for BeginnersGuide to Install and Set up Android StudioHow to Create/Start a New Project in Android Studio?Running your first Android appHow to add Lottie Animation in an Android AppMediaPlayer Class in Android In this article, we are going to bui
12 min read
Complete guide on How to build a Video Player in Android
This article explains the stepwise process as to how to build a Video Player using Android Studio. For viewing videos in android, there is a special class called "Exoplayer". In this article, we will be having 2 videos which are connected by the "Dialog box", i.e. a dialog box will come after comple
5 min read
How to Build a Simple TikTok Clone Android App using Firebase?
TikTok is a mobile application that can be downloaded on smartphones and tablets. It is available on both iOS and Android operating systems and can be downloaded for free from the respective app stores. TikTok is a social media platform where users can view short video content i.e. 15 to 60 secs. A
5 min read
How to Build a Photo Viewing Application in Android?
Gallery app is one of the most used apps which comes pre-installed on many Android devices and there are several different apps that are present in Google Play to view the media files present in your device. In this article, we will be simply creating a Gallery app in which we can view all the photo
8 min read
How to Build a Video Calling Android App with Jitsi Meet SDK?
Video Calling has become a most demanding feature in many social media apps like WhatsApp, Instagram, Facebook, etc. Not only this but also there are some other applications available for providing only this feature to connect people all over the world with each other like Duo. Hence, this gives us
4 min read
How to Capture HDR Videos in Android 13?
You can preview and capture HDR video material with your camera thanks to the Camera2 APIs' support for high dynamic range (HDR) video capture. The video which is taken in HDR is way ahead of the Standard Video that your current app is currently rendering, and is a must to use if the user's device s
4 min read
How to Build a Bitcoin Tracker Android App?
In this article, we will be building a Bitcoin Tracker Project using Java/Kotlin and XML in Android. The application will display the current rates of Bitcoin in different countries using Bitcoin API. There are many free APIs available and for this project, we will be using API by Coinlayer. The API
7 min read
How to Convert a Vector to Bitmap in Android?
A vector is a set of points, lines, and colors associated with any image object defined inside an XML file. All these associated attributes are compiled in real-time to develop an image object. Simply, a vector is a coded representation of an image object. Bitmap, also known as bitmap index or bit a
3 min read
How to Build a Photo Viewing Application in Android using Jetpack Compose?
Gallery App is one of the most used Applications which comes pre-installed on many Android devices and there are several different applications that are present in Google Play to view the media files present in a device. In this article, we will be building a simple Gallery Application for Android u
10 min read