如何由图片制作MP4文件?

19

有人能告诉我如何在安卓上合并图片并生成一个mp4文件,并将视频文件存储在SD卡中吗?


你可以给FFmpeg一个机会。 - pskink
1
但它是一个NDK库,我希望只使用SDK来完成所有这些事情。 - Rohit Heera
你可以使用jcodec的SequenceEncoder。https://dev59.com/3HrZa4cB1Zd3GeqPyiG4#20630238 - Abhishek V
1
最低要求为2.3奶油三明治版本(ICS是4.0版本,2.3是姜饼版本,请参考此处)。 - 2Dee
请访问此链接:https://dev59.com/vmPVa4cB1Zd3GeqP1wd0 - Bhaskar Kumar Singh
显示剩余3条评论
3个回答

9
请查看下面的代码
创建一个名为FfmpegController.java的文件。
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.e("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");
    }
}

创建另一个名为Utility.java的Java文件。

public class Utility {

    private final static String TAG = Utility.class.getName();
    private static Context mContext;

    public Utility(Context context) {
        mContext = context;
    }

    public static String excuteCommand(String command)
    {
        try {
            Log.d(TAG, "execute command : " + command);

            Process process = Runtime.getRuntime().exec(command);

            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream()));
            int read;
            char[] buffer = new char[4096];
            StringBuffer output = new StringBuffer();
            while ((read = reader.read(buffer)) > 0) {
                output.append(buffer, 0, read);
            }
            reader.close();

            process.waitFor();

            Log.d(TAG, "command result: " + output.toString());

            return output.toString();

        } catch (IOException e) {

            Log.e(TAG, e.getMessage(), e);

        } catch (InterruptedException e) {

            Log.e(TAG, e.getMessage(), e);
        }

        return "";
    }

    public String getPathOfAppInternalStorage()
    {
        return mContext.getApplicationContext().getFilesDir().getAbsolutePath();
    }

    public void saveFileToAppInternalStorage(InputStream inputStream, String fileName)
    {
        File file = new File(getPathOfAppInternalStorage() + "/" + fileName);
        if (file.exists())
        {
            Log.d(TAG, "SaveRawToAppDir Delete Exsisted File");
            file.delete();
        }

        FileOutputStream outputStream;
        try {
            outputStream = mContext.openFileOutput(fileName, Context.MODE_PRIVATE);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) > 0)
            {
                outputStream.write(buffer, 0, length);
            }
            outputStream.close();
            inputStream.close();
        } catch (Exception e) {
            Log.e(TAG, e.getMessage(), e);
        }
    }

    public static boolean isFileExsisted(String filePath)
    {
        File file = new File(filePath);
        return file.exists();
    }

    public static void deleteFileAtPath(String filePath)
    {
        File file = new File(filePath);
        file.delete();
    }
}

创建另一个文件 CommandHelper.java
public class CommandHelper {
    public static String commandConvertImgToVideo(String ffmpegBinaryPath, String inputImgPath, String outputVideoPath) {
        Log.e("ffmpegBinaryPath", "ffmpegBinaryPath - "+ffmpegBinaryPath);
        Log.e("inputImgPath", "inputImgPath - "+inputImgPath);
        Log.e("outputVideoPath", "outputVideoPath - "+outputVideoPath);

        return ffmpegBinaryPath + " -r 1/1 -i " + inputImgPath + " -c:v libx264 -crf 23 -pix_fmt yuv420p -s 640x480 " + outputVideoPath;
    }

    public static String commandChangeFilePermissionForExecuting(String filePath) {
        return "chmod 777 " + filePath;
    }
}

如果您想执行代码并将图像转换为视频,请使用以下代码。

AsyncTask asyncTask = new AsyncTask() {

         ProgressDialog mProgressDialog;

         @Override
         protected void onPreExecute() {
            /* mProgressDialog = new ProgressDialog(activity.this);

             mProgressDialog.setMessage("Converting...");

             mProgressDialog.setCancelable(false);

             mProgressDialog.show();*/

             Log.e("Video Process Start", "======================== Video Process Start ======================================");
         }

         @Override
         protected Object doInBackground(Object... params) {

            saveInputImgToAppInternalStorage();
/*           for(int i = 1; i<11 ; i++){
             mFfmpegController.convertImageToVideo(mUtility.getPathOfAppInternalStorage() + "/" + "Img"+i+".jpg");
             }
*/

            mFfmpegController.convertImageToVideo(mUtility.getPathOfAppInternalStorage() + "/" + "img%05d.jpg");
             return null;
         }

         @Override
         protected void onPostExecute(Object o) {
            // mProgressDialog.dismiss();
             Log.e("Video Process Complete", "======================== Video Process Complete ======================================");

             Log.e("Video Path", "Path - "+mFfmpegController.pathOuputVideo());

             Toast.makeText(activity.this, "Video Process Complete", Toast.LENGTH_LONG).show();
             stopSelfResult(lateststartid);
             Common.ScreenshotCounter = 0;
             Common.ScreenshotTimerCounter = 0;
             /*try {
                copyFile(new FileInputStream(mFfmpegController.pathOuputVideo()), new FileOutputStream(Common.strPathForVideos));
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }*/

         }
     };

请注意:
捕获的图像必须是以下格式: Img00001,Img00002...... 因为FFMPEG代码期望它是这样的。
对于那些找不到R.raw.ffmpeg的人: 前往:https://github.com/guardianproject/android-ffmpeg-java/blob/master/res/raw/ffmpeg

6
ffmpeg 是在 R.raw.ffmpeg 中的一个文件。 - Kuls
1
运行此控制器是否需要针对不同平台架构拥有FFmpeg二进制文件? - Shubham AgaRwal
如何在原始代码中添加FFmpeg,添加后显示未知格式。 - varun setia

4
有很多编辑视频的工具,例如INDEFFMPEG等等。
INDE有许多功能可以用于合并视频和图片。
如果您决定使用FFMPEG,那么这个链接提供了集成此工具的步骤。
其他有用的链接:
- FFMPEG:多个图像帧+ 1个音频= 1个视频 - Android从图像列表创建动画视频 - Android ffmpeg:使用jni从图像序列创建视频 - 将图像与音频文件组合并在Android中编程创建视频文件 - 如何从一系列图像中创建视频? - 如何通过示例基于FFmpeg构建Android应用程序

2

1
该库在其常见问题解答中提到,无法将图片合并成视频。 - Oximer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接