티스토리 뷰

FFMpeg를 이용해 안드로이드 동영상 편집 앱 만들기 

동영상 편집앱 - Trim 기능 (자르기) 

AndroidManifest.xml 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.jwlee.jwvideo">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".ProgressBarActivity"></activity>
        <activity android:name=".TrimActivity" />
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".FFMpegService"></service>
    </application>

</manifest>

 

build gradle(Module)

apply plugin: 'com.android.application'

android {
    compileSdkVersion 29

    defaultConfig {
        applicationId "com.jwlee.jwvideo"
        minSdkVersion 16
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation 'org.florescu.android.rangeseekbar:rangeseekbar-library:0.3.0'
    implementation 'com.dinuscxj:circleprogressbar:1.3.0'
    implementation 'android.arch.lifecycle:extensions:1.1.1'
    implementation 'com.intuit.sdp:sdp-android:1.0.6'
    implementation 'com.writingminds:FFmpegAndroid:0.3.2'

}

build gradle(Project)

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:4.0.0"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        maven()
                {
                    url "https://maven.google.com"
                }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

 

XML Code - activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    tools:context=".MainActivity">

   <Button
       android:onClick="openVideo"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Pick video"
       />

</RelativeLayout>

 

XML Code - activity_progress_bar.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    tools:context=".ProgressBarActivity">
    
    <com.dinuscxj.progressbar.CircleProgressBar
        android:layout_width="@dimen/_100sdp"
        android:layout_height="@dimen/_100sdp"
        android:layout_marginTop="20dp"
        app:progress_end_color="@android:color/transparent"
        app:progress_stroke_width="10dp"
        app:progress_text_color="#fff"
        android:layout_centerInParent="true"
        app:style="solid_line"
        android:id="@+id/circleProgressBar"
        />

</RelativeLayout>

XML Code - activity_trim.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    tools:context=".TrimActivity">

    <VideoView
        android:id="@+id/videoView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <ImageView
        android:id="@+id/pause"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:src="@drawable/ic_pause"/>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="@dimen/_90sdp"
        android:layout_alignParentBottom="true"
        android:background="@color/colorPrimary"
        >
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/tvvLeft"
            android:textSize="@dimen/_10sdp"
            android:layout_marginLeft="@dimen/_10sdp"
            android:text="00:00:00"
            android:layout_below="@+id/seekbar"
            />
        <TextView
            android:id="@+id/tvvRight"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_marginRight="17dp"
            android:layout_below="@+id/seekbar"
            android:gravity="end"
            android:textSize="17sp"
            android:text="00:00:00"
            android:layout_alignParentRight="true"
            />

        <org.florescu.android.rangeseekbar.RangeSeekBar
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginRight="17dp"
            rsb_indicator_text_color="#fff"
            rsb_progress_color = "@color/colorPrimaryDark"
            rsb_progress_default_color="@color/colorPrimaryDark"
            android:layout_marginLeft="17dp"
            rsb_tick_mark_text_color = "@color/colorPrimaryDark"
            android:layout_centerInParent="true"
            android:id="@+id/seekbar"

            />



    </RelativeLayout>

</RelativeLayout>

 

res - menu - menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/trim"
        android:title="Trim"
        app:showAsAction="always"></item>

</menu>

 

Java Code - FFMpegService

package com.jwlee.jwvideo;

import android.app.Activity;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

import androidx.annotation.Nullable;
import androidx.lifecycle.MutableLiveData;

import com.github.hiteshsondhi88.libffmpeg.ExecuteBinaryResponseHandler;
import com.github.hiteshsondhi88.libffmpeg.FFmpeg;
import com.github.hiteshsondhi88.libffmpeg.LoadBinaryResponseHandler;
import com.github.hiteshsondhi88.libffmpeg.exceptions.FFmpegCommandAlreadyRunningException;
import com.github.hiteshsondhi88.libffmpeg.exceptions.FFmpegNotSupportedException;

import javax.security.auth.callback.Callback;

public class FFMpegService extends Service {

    FFmpeg fFmpeg;
    int duration;

    String[] command;
    Callbacks activity;

    public MutableLiveData<Integer> percentage;
    IBinder myBinder = new LocalBinder();

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        if(intent != null)
        {
            duration = Integer.parseInt(intent.getStringExtra("duration"));
            command = intent.getStringArrayExtra("command");
            try {
                loadFFMpegBinary();
                execFFMpegCommand();
                
            } catch (FFmpegNotSupportedException e) {
                e.printStackTrace();
            } catch (FFmpegCommandAlreadyRunningException e) {
                e.printStackTrace();
            }


        }
        return super.onStartCommand(intent, flags, startId);
    }

    private void execFFMpegCommand() throws FFmpegCommandAlreadyRunningException {
        fFmpeg.execute(command,new ExecuteBinaryResponseHandler(){
            @Override
            public void onFailure(String message){
                super.onFailure(message);
            }

            @Override
            public void onSuccess(String message){
                super.onSuccess(message);
            }

            @Override
            public void onProgress(String message){
                String arr[];
                if(message.contains("time=")){
                    arr = message.split("time=");
                    String yalo = arr[1];
                    String abikamha[] = yalo.split(":");
                    String[] yaenda = abikamha[2].split(" ");
                    String seconds = yaenda[0];

                    int hours = Integer.parseInt(abikamha[0]);
                    hours = hours * 3600;
                    int min = Integer.parseInt(abikamha[1]);
                    min = min * 60;
                    float sec = Float.valueOf(seconds);

                    float timeInSec = hours+min+sec;

                    percentage.setValue((int)((timeInSec/duration)*100));
                }

            }

            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onFinish() {
                percentage.setValue(100);
            }
        });

    }

    @Override
    public void onCreate() {
        super.onCreate();
        try{
            loadFFMpegBinary();
        }catch (FFmpegNotSupportedException e){
            e.printStackTrace();
        }

        percentage = new MutableLiveData<>();
    }

    private void loadFFMpegBinary() throws FFmpegNotSupportedException {
        if (fFmpeg == null) {
            fFmpeg = fFmpeg.getInstance(this);
        }

        fFmpeg.loadBinary(new LoadBinaryResponseHandler() {
            @Override
            public void onFailure() {
                super.onFailure();
            }

            @Override
            public void onSuccess() {
                super.onSuccess();
            }
        });
    }

    public FFMpegService() {
        super();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return myBinder;
    }

    public class LocalBinder extends Binder {
        public FFMpegService getServiceInstance() {
            return FFMpegService.this;
        }
    }

    public void registerClient(Activity activity) {
        this.activity = (Callbacks) activity;

    }

    public MutableLiveData<Integer> getPercentage() {
        return percentage;

    }

    public interface Callbacks {
        void updateClient(float data);

    }
}

aㅁ

Java Code - MainActivity

package com.jwlee.jwvideo;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    Uri selectedUri;

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

    public void openVideo(View v){
        Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        i.setType("video/*");
        startActivityForResult(i,100);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 100 && resultCode == RESULT_OK){
            selectedUri = data.getData();

            Intent i = new Intent(MainActivity.this,TrimActivity.class);
            i.putExtra("uri",selectedUri.toString());
            startActivity(i);

        }

    }
}

 

Java Code - ProgressBarActivity

package com.jwlee.jwvideo;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Toast;

import com.dinuscxj.progressbar.CircleProgressBar;

public class ProgressBarActivity extends AppCompatActivity {

    CircleProgressBar circleProgressBar;
    int duration;
    String[] command;
    String path;

    ServiceConnection mConnection;
    FFMpegService ffMpegService;
    Integer res;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_progress_bar);
        circleProgressBar = findViewById(R.id.circleProgressBar);
        circleProgressBar.setMax(100);

       final Intent i = getIntent();

        if(i!=null)
        {
            duration = i.getIntExtra("duration",0);
            command = i.getStringArrayExtra("command");
            path = i.getStringExtra("destination");

            final Intent myIntent = new Intent(ProgressBarActivity.this, FFMpegService.class);
            myIntent.putExtra("duration",String.valueOf(duration));
            myIntent.putExtra("command",command);
            myIntent.putExtra("destination",path);
            startService(myIntent);

            mConnection = new ServiceConnection() {
                @Override
                public void onServiceConnected(ComponentName name, IBinder iBinder) {
                    FFMpegService.LocalBinder binder = (FFMpegService.LocalBinder)iBinder;
                    ffMpegService = binder.getServiceInstance();
                    ffMpegService.registerClient(getParent());

                    final Observer<Integer> resultObserver = new Observer<Integer>() {
                        @Override
                        public void onChanged(Integer integer) {
                            res = integer;

                            if(res < 100){
                                circleProgressBar.setProgress(res);
                            }

                            if(res ==100)
                            {
                                circleProgressBar.setProgress(res);
                                stopService(myIntent);
                                Toast.makeText(getApplicationContext(),"Video Trimmed successfully",Toast.LENGTH_LONG).show();
                            }

                        }
                    };

                    ffMpegService.getPercentage().observe(ProgressBarActivity.this,resultObserver);



                }

                @Override
                public void onServiceDisconnected(ComponentName name) {

                }
            };

            bindService(myIntent,mConnection, Context.BIND_AUTO_CREATE);



        }
    }
}

 

Java Code - TrimActivity

package com.jwlee.jwvideo;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.InputType;
import android.util.Log;
import android.util.Range;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.VideoView;

import org.florescu.android.rangeseekbar.RangeSeekBar;

import java.io.File;

public class TrimActivity extends AppCompatActivity {

    Uri uri;
    ImageView imageView;
    VideoView videoView;
    TextView textViewLeft, textViewRight;
    RangeSeekBar rangeSeekBar;
    boolean isPlaying = false;

    int duration;
    String filePrefix;
    String[] command;
    File dest;
    String original_path;


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

        imageView = (ImageView) findViewById(R.id.pause);
        videoView = (VideoView) findViewById(R.id.videoView);
        textViewRight = (TextView) findViewById(R.id.tvvRight);
        textViewLeft = (TextView) findViewById(R.id.tvvLeft);
        rangeSeekBar = (RangeSeekBar) findViewById(R.id.seekbar);

        Intent i = getIntent();

        if (i != null) {
            String imgPath = i.getStringExtra("uri");
            uri = Uri.parse(imgPath);
            isPlaying = true;
            videoView.setVideoURI(uri);
            videoView.start();
        }

        setListeners();
    }

    private void setListeners() {
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isPlaying) {
                    imageView.setImageResource(R.drawable.ic_play);
                    videoView.pause();
                    isPlaying = false;
                } else {
                    videoView.start();
                    imageView.setImageResource(R.drawable.ic_pause);
                    isPlaying = true;
                }

            }
        });


        videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                videoView.start();
                duration = mp.getDuration() / 1000;
                textViewLeft.setText("00:00:00");
                textViewRight.setText(getTime(mp.getDuration() / 1000));
                mp.setLooping(true);
                rangeSeekBar.setRangeValues(0, duration);
                rangeSeekBar.setSelectedMaxValue(duration);
                rangeSeekBar.setSelectedMinValue(0);
                rangeSeekBar.setEnabled(true);
                rangeSeekBar.setOnRangeSeekBarChangeListener(new RangeSeekBar.OnRangeSeekBarChangeListener() {
                    @Override
                    public void onRangeSeekBarValuesChanged(RangeSeekBar bar, Object minValue, Object maxValue) {
                        videoView.seekTo((int) minValue * 1000);
                        textViewLeft.setText(getTime((int) bar.getSelectedMinValue()));
                        textViewRight.setText(getTime((int) bar.getSelectedMaxValue()));

                    }
                });

                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (videoView.getCurrentPosition() >= rangeSeekBar.getSelectedMaxValue().intValue() * 1000)
                            videoView.seekTo(rangeSeekBar.getSelectedMinValue().intValue() * 1000);


                    }
                }, 1000);
            }
        });
    }

    private String getTime(int seconds) {
        int hr = seconds / 3600;
        int rem = seconds % 3600;
        int mn = rem / 60;
        int sec = rem % 60;
        return String.format("%02d", hr) + ":" + String.format("%02d", mn) + ":" + String.format("%02d", sec);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == R.id.trim) {
            final AlertDialog.Builder alert = new AlertDialog.Builder(TrimActivity.this);
            LinearLayout linearLayout = new LinearLayout(TrimActivity.this);
            linearLayout.setOrientation(LinearLayout.VERTICAL);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
            lp.setMargins(50, 0, 50, 100);
            final EditText input = new EditText(TrimActivity.this);
            input.setLayoutParams(lp);
            input.setGravity(Gravity.TOP | Gravity.START);
            input.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
            linearLayout.addView(input, lp);

            alert.setMessage("Set video name?");
            alert.setTitle("Change video name");
            alert.setView(linearLayout);
            alert.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();

                }
            });

            alert.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    filePrefix = input.getText().toString();

                    trimVideo(rangeSeekBar.getSelectedMinValue().intValue() * 1000,
                            rangeSeekBar.getSelectedMaxValue().intValue() * 1000, filePrefix);

                    Intent intent = new Intent(TrimActivity.this, ProgressBarActivity.class);
                    intent.putExtra("duration", duration);
                    intent.putExtra("command", command);
                    intent.putExtra("destination", dest.getAbsolutePath());
                    startActivity(intent);

                    finish();
                    dialog.dismiss();


                }
            });

            alert.show();


        }
        return super.onOptionsItemSelected(item);
    }

    private File trimVideo(int startMs, int endMs, String filename) {
        File folder = new File(Environment.getExternalStorageDirectory() + "/TrimVideos");
        if (!folder.exists()) {
            folder.mkdir();
            Log.d("테스트", "폴더생성");
        }

        filePrefix = filename;

        String fileExt = ".mp4";
        dest = new File(folder, filePrefix + fileExt);
        original_path = getRealPathFromUri(getApplicationContext(), uri);

        duration = (endMs - startMs) / 1000;
        command = new String[]{"-ss", "" + startMs / 1000, "-y", "-i", original_path, "-t", "" + (endMs - startMs) / 1000,
                "-vcodec", "mpeg4", "-b:v", "2097152", "-b:a", "48000", "-ac", "2", "-ar", "22050", dest.getAbsolutePath()};


        return folder;


    }

    private String getRealPathFromUri(Context context, Uri contentUri) {
        Cursor cursor = null;

        try {
            String[] proj = {MediaStore.Images.Media.DATA};
            cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

            cursor.moveToFirst();
            return cursor.getString(column_index);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }
}

 

댓글
최근에 달린 댓글
글 보관함
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Total
Today
Yesterday
    뽀로로친구에디
    최근에 올라온 글