마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

FFmpeg로 변환한 동영상 저장 경로를 찾지 못하는 것 같습니다.

0 추천

FFmpeg를 이용하여 이미지들을 동영상으로 변환하고자 하는데 동영상 경로를 못 잡는것 같습니다.
경로에 관련된 것들을 찬찬히 봤는데도 디버그 하기가 도저히 까다로워서 여기에 조언을 구합니다.

<실행 프로세스>

1. 출발지와 도착지를 입력하고, 최단경로 좌표를 파싱하여 Java 단으로 전송.
2. tokenizer를 이용해 배열에 하나씩 저장하고, url에 매핑된 이미지를 다운로드 수행.
3. 이미지들을 FFmpeg 명령어를 이용하여 동영상으로 재생.

2번까지는 잘 되는 것 같아 보입니다. 확인 한번 부탁드립니다. 
감사합니다.

 

MyActivity.java에서 이미지 다운받는 부분 및 2개의 java 소스는 용량 관계 상 첨부하지 않았습니다.
필요하시다면 올려드리겠습니다. !

MyActivity.java

public class MyActivity extends Activity {
 
    private static VideoView mVideoView;
    private static FfmpegController mFfmpegController;
    private static Utility mUtility;
    private WebView webView;
 
    // File myDir = getDir("testdir", Activity.MODE_PRIVATE);
    // String myPath = myDir.getAbsolutePath();
 
    String UrlString[] = new String[300];
    String RealUrlString[] = new String[200];
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initInstances();
        initUi();
    }
 
    private void initUi() {
 
        setContentView(R.layout.main);
 
        webView = (WebView) findViewById(R.id.webview);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.addJavascriptInterface(new MyJavaScriptInterface(this), "HtmlViewer");
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                if (url.contains("mapdata")) {
                    webView.setVisibility(View.GONE);
                    webView.loadUrl("javascript:window.HtmlViewer.showHTML"
                            + "(document.getElementsByTagName('html')[0].innerHTML);");
                }
            }
        });
        // webView.addJavascriptInterface(obj, interfaceName);
        webView.loadUrl("http://39.120.204.201/dgcse/psm/finalProject.html");
        mVideoView = (VideoView) findViewById(R.id.videoView);
        mImageView = (ImageView) findViewById(R.id.imageView);
    }
 
    private void initInstances() {
        mFfmpegController = new FfmpegController(this);
        mUtility = new Utility(this);
    }
 
    class MyJavaScriptInterface {
        private Context ctx;
 
        MyJavaScriptInterface(Context ctx) {
            this.ctx = ctx;
        }
 
        public void showHTML(String html) throws InterruptedException {
            int i = 0;
            Toast.makeText(getApplicationContext(), html, Toast.LENGTH_LONG).show();
            StringTokenizer tmpStr = new StringTokenizer(html, ",");
 
                while (tmpStr.hasMoreElements()) {
                    UrlString[i] = (String) tmpStr.nextElement();
                    i++;
                }
         
                 
 
            i = 0;
 
            while (i < 100) {
                RealUrlString[i] = UrlString[2 * i] + UrlString[2 * i + 1];
                new HttpReqTask().execute(RealUrlString[i], "img0000" + i);
                i++;
            }
 
            Toast.makeText(getApplicationContext(), RealUrlString[3], Toast.LENGTH_LONG).show();
        }
    }
 
    public void onClickConvertImg2Video(View view) {
 
        // It takes a long time to convert images into a video, So we add
        // loading progress dialog while converting.
 
        AsyncTask asyncTask = new AsyncTask() {
            ProgressDialog mProgressDialog;
 
            @Override
            protected void onPreExecute() {
                mProgressDialog = new ProgressDialog(MyActivity.this);
                mProgressDialog.setMessage("Converting...");
                mProgressDialog.setCancelable(false);
                mProgressDialog.show();
            }
 
            @Override
            protected Object doInBackground(Object... params) {
                //saveInputImgToAppInternalStorage();
                // important!!
                // 위에 꺼가 raw source
                mFfmpegController.convertImageToVideo(mUtility.getPathOfAppInternalStorage() + "/" + "img%05d.jpg");
                mFfmpegController.convertImageToVideo(getApplicationContext().getFilesDir().getAbsolutePath() + "/" + "img%05d.jpg");
                 
                return null;
            }
 
            @Override
            protected void onPostExecute(Object o) {
                Log.e("tag",
                        "======================== Video Process Complete ======================================");
                Log.e("Video Path", "Path - " + mFfmpegController.pathOuputVideo());
                mProgressDialog.dismiss();
            }
        };
        asyncTask.execute();
    }
 
    public void onClickPlayVideo(View view) {
        playVideo();
    }
 
    public void playVideo() {
        mVideoView.setVideoPath(mFfmpegController.pathOuputVideo());
        mVideoView.start();
    }
 
    private String saveToInternalStorage(Bitmap bitmapImage) {
        ContextWrapper cw = new ContextWrapper(getApplicationContext());
        // path to /data/data/yourapp/app_data/imageDir
        File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
        // Create imageDir
        File mypath = new File(directory, "profile.jpg");
 
        FileOutputStream fos = null;
        try {
 
            fos = new FileOutputStream(mypath);
 
            // Use the compress method on the BitMap object to write image to
            // the OutputStream
            bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return directory.getAbsolutePath();
    }
 
    private void saveInputImgToAppInternalStorage() {
        /*
         * The testing images in R.raw will be saved into the app internal
         * storage, so we can use ffmpeg command to convert images into an
         * video.
         */
 
        for (int i = 0; i <= 10; i++) {
            String imgName = String.format("img%05d", i);
            int imgResId = getResources().getIdentifier(imgName, "raw", getPackageName());
 
            mUtility.saveFileToAppInternalStorage(getResources().openRawResource(imgResId), imgName + ".bmp");
 
        }
    }
}

FfmpegController.java

package com.wani.img2video;
 
import java.io.ByteArrayInputStream;
import java.io.InputStream;
 
import com.example.img2video.R;
 
import android.content.Context;
import android.util.Log;
 
 
public class FfmpegController {
 
    private static Context mContext;
    private static Utility mUtility;
    private static String mFfmpegBinaryPath;
 
    public FfmpegController(Context context) {
 
        mContext = context;
        mUtility = new Utility(context);
        initFfmpeg();
    }
 
    private void initFfmpeg()
    {
        /*
        Save the ffmpeg binary to app internal storage, so we can use it by executing java runtime command.
         */
 
        mFfmpegBinaryPath = mContext.getApplicationContext().getFilesDir().getAbsolutePath() + "/ffmpeg";
 
        if (Utility.isFileExsisted(mFfmpegBinaryPath))
            return;
 
        InputStream inputStream = mContext.getResources().openRawResource(R.raw.ffmpeg);
        mUtility.saveFileToAppInternalStorage(inputStream, "ffmpeg");
        Utility.excuteCommand(CommandHelper.commandChangeFilePermissionForExecuting(mFfmpegBinaryPath));
    }
 
    public void convertImageToVideo(String inputImgPath)
    {
        /*
        Delete previous video.
         */
 
        Log.d("Image Parth", "inputImgPath - "+inputImgPath);
 
        if (Utility.isFileExsisted(pathOuputVideo()))
            Utility.deleteFileAtPath(pathOuputVideo());
 
        /*
        Save the command into a shell script.
         */
 
        saveShellCommandImg2VideoToAppDir(inputImgPath);
 
        Utility.excuteCommand("sh" + " " + pathShellScriptImg2Video());
    }
 
    public String pathOuputVideo()
    {
        return mUtility.getPathOfAppInternalStorage() + "/out.mp4";
    }
 
    private String pathShellScriptImg2Video()
    {
        return mUtility.getPathOfAppInternalStorage() + "/img2video.sh";
    }
 
    private void saveShellCommandImg2VideoToAppDir(String inputImgPath)
    {
        String command = CommandHelper.commandConvertImgToVideo(mFfmpegBinaryPath, inputImgPath, pathOuputVideo());
        InputStream is = new ByteArrayInputStream(command.getBytes());
        mUtility.saveFileToAppInternalStorage(is, "img2video.sh");
    }
}
드록바터닝슛 (140 포인트) 님이 2015년 11월 1일 질문

1개의 답변

0 추천
기다리시는 답변이 아니라 죄송합니다.

다름이 아니라, 사용하신 기능에 대해 관심이 많은 개발자입니다.

VLC 도 다뤄보았지만, FFMEPG 는 도통 손에 익지를 않네요.

저도 마찬가지로 FFMPEG로 이미지를 모아 영상을 만들어보고자 합니다.

참고하신 출처가 있다면 조언 부탁드립니다.
익명사용자 님이 2015년 11월 2일 답변
아 저는 FFmpeg를 전문적으로 이용해서 뭘 해보려는건 아니고
딱 지금 하는 기능만 필요한데 이것도 쉽지 않네요 ㅜ_ㅜ...

http://www.androidpub.com/index.php?mid=android_dev_info&page=1&search_target=tag&search_keyword=FFmpeg&document_srl=1645684

'안드로이드 펍' 남은그루터기님의 강좌이구요

안드로이드에서 사용하실거면

https://github.com/DreaMarch/android-ffmpeg-img2video
(Github, Eclipse용)

안드로이드 스튜디오 용은 따로 있던데 잘 모르겠구요

마지막으로 역시 FFMPEG 공식 홈페이지가 도움이 되겠지만 워낙 영어가 많아서 저는 읽기에 엄두가 안났습니다.
답변 감사합니다.
큰 도움이 될 것 같습니다.
...