📜  如何构建一个 Android 应用来压缩视频?

📅  最后修改于: 2022-05-13 01:54:22.071000             🧑  作者: Mango

如何构建一个 Android 应用来压缩视频?

如今,我们看到许多应用程序用于压缩视频和其他文件,以便用户可以节省内存并保持该文件的质量。在本文中,我们将了解如何在 android studio 中压缩视频,并制作我们自己的视频压缩应用程序。

我们将在本文中构建什么?

下面是我们将在本文中构建的视频压缩器的示例视频。请注意,我们将使用Java语言来实现这个项目。

分步实施

步骤 1:创建一个新项目

  • 打开一个新项目。
  • 我们将使用Java语言开发 Empty Activity。保持所有其他选项不变。
  • 您可以在方便时更改项目的名称。
  • 将有两个名为activity_main.xmlMainActivity 的默认文件。Java

如果您不知道如何在 Android Studio 中创建新项目,可以参考如何在 Android Studio 中创建/启动新项目?

第 2 步:添加所需的依赖项

打开 Gradle 脚本 > build.gradle(module)。并在其中使用以下依赖项-

implementation 'com.iceteck.silicompressorr:silicompressor:2.2.4'
implementation 'com.googlecode.mp4parser:isoparser:1.1.22'

单击立即同步以保存更改。

第 3 步:添加所需的权限

打开 AndroidManifest.xml 文件并为其添加以下权限 -


第 4 步:使用 xml 文件

导航到app > res > layout > activity_main.xml并将以下代码添加到该文件。下面是 activity_main.xml 文件的代码。

XML


  
    


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 {
  
        // 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));
        }
    }
}


第 5 步:使用Java文件

转到MainActivity。 Java文件并参考以下代码。下面是 MainActivity 的代码。 Java文件。代码中添加了注释以更详细地理解代码。

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 {
  
        // 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));
        }
    }
}

这是我们应用程序的最终输出。

输出: