如何以编程方式在Android中附加两个视频

时间:2014-02-04 12:22:57

标签: android video append mediarecorder android-mediarecorder

我正在使用此代码。我需要合并两个视频。它将所有视频保存在临时文件夹中,但未保存在合并条件下。 Append和DoAppend是我想要合并视频的功能。

public String append(ArrayList<String> trimVideos) {

        for (int i = 0; i < trimVideos.size() - 1; i++) {

      String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
     if (i == 0) {                      
            String OutPutFileName = Constants.STORAGE_VIDEO_TEMP_PATH +                           
            File.separator + "APPEND" + "_" + timeStamp + ".mp4";
            doAppend(trimVideos.get(0), trimVideos.get(i + 1),OutPutFileName);
            Log.e(Constants.TAG, "In First: " + i + " " +   OutPutFileName);

                  } else {

        String OutPutFileName = Constants.STORAGE_VIDEO_TEMP_PATH
    + File.separator + "APPEND" + i + "_" + timeStamp + ".mp4";
                    doAppend(lastAppendOut, trimVideos.get(i + 1), OutPutFileName);
                    Log.e(Constants.TAG, "In Second: " + i + " " + OutPutFileName);
                }
            }
            Log.e(Constants.TAG, "In End: "  + " " + lastAppendOut);
            return lastAppendOut;
        }

此方法在添加曲目时崩溃了我的应用程序。

private String doAppend(String _firstVideo, String _secondVideo,String _newName) {
        try {

            Log.e("test", "Stage1");
            FileInputStream fis1 = new FileInputStream(_firstVideo);
            FileInputStream fis2 = new FileInputStream(_secondVideo);

            Movie[] inMovies = new Movie[] {
                    MovieCreator.build(fis1.getChannel()),MovieCreator.build(fis2.getChannel()) };

            List<Track> videoTracks = new LinkedList<Track>();
            List<Track> audioTracks = new LinkedList<Track>();
    //It returns one item of video and 2 item of video.

            for (Movie m : inMovies) {
                for (Track t : m.getTracks()) {
                    if (t.getHandler().equals("soun")) {
                        audioTracks.add(t);
                    }
                    if (t.getHandler().equals("vide")) {
                        videoTracks.add(t);
                    }
                }
            }
            Log.e("test", "Stage2");
            Movie result = new Movie();


            if (audioTracks.size() > 0) {
                result.addTrack(new AppendTrack(audioTracks.toArray(new Track[audioTracks.size()])));
            }
            if (videoTracks.size() > 0) {

            result.addTrack(new AppendTrack(videoTracks.toArray(new Track[videoTracks.size()])));
            }

            IsoFile out = new DefaultMp4Builder().build(result);
            Log.e("test", "Stage3");
            String filename = _newName;
            lastAppendOut = filename;
            Log.e(Constants.TAG, "In Append: "  + " " + lastAppendOut);

            FileOutputStream fos = new FileOutputStream(filename);
            FileChannel fco = fos.getChannel();

            fco.position(0);
            out.getBox(fco);
            fco.close();
            fos.close();
            fis1.close();
            fis2.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("check", e.getMessage());
        }
        return _newName;
    }

3 个答案:

答案 0 :(得分:5)

合并多个视频的代码

public class MergeVideo extends AsyncTask<String, Integer, String> {

    @Override
    protected void onPreExecute() {
        progressDialog = ProgressDialog.show(Video.this,
                "Preparing for upload", "Please wait...", true);
        // do initialization of required objects objects here
    };

    @Override
    protected String doInBackground(String... params) {
        try {
            String paths[] = new String[count];
            Movie[] inMovies = new Movie[count];
            for (int i = 0; i < count; i++) {
                paths[i] = path + filename + String.valueOf(i + 1) + ".mp4";
                inMovies[i] = MovieCreator.build(new FileInputStream(
                        paths[i]).getChannel());
            }
            List<Track> videoTracks = new LinkedList<Track>();
            List<Track> audioTracks = new LinkedList<Track>();
            for (Movie m : inMovies) {
                for (Track t : m.getTracks()) {
                    if (t.getHandler().equals("soun")) {
                        audioTracks.add(t);
                    }
                    if (t.getHandler().equals("vide")) {
                        videoTracks.add(t);
                    }
                }
            }

            Movie result = new Movie();

            if (audioTracks.size() > 0) {
                result.addTrack(new AppendTrack(audioTracks
                        .toArray(new Track[audioTracks.size()])));
            }
            if (videoTracks.size() > 0) {
                result.addTrack(new AppendTrack(videoTracks
                        .toArray(new Track[videoTracks.size()])));
            }

            BasicContainer out = (BasicContainer) new DefaultMp4Builder()
                    .build(result);

            @SuppressWarnings("resource")
            FileChannel fc = new RandomAccessFile(String.format(Environment
                    .getExternalStorageDirectory() + "/wishbyvideo.mp4"),
                    "rw").getChannel();
            out.writeContainer(fc);
            fc.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String mFileName = Environment.getExternalStorageDirectory()
                .getAbsolutePath();
        mFileName += "/wishbyvideo.mp4";
        filename = mFileName;
        return mFileName;
    }

    @Override
    protected void onPostExecute(String value) {
        super.onPostExecute(value);
        progressDialog.dismiss();
        Intent i = new Intent(Video.this, VideoUpload.class);
        i.putExtra("videopath", value);
        i.putExtra("id", id);
        i.putExtra("name", name);
        i.putExtra("photo", photo);
        startActivity(i);
        finish();
    }
}

计数只是视频文件计数。

答案 1 :(得分:1)

上述答案完全正确,但只有在您的媒体编码器为H264时才会有效.....

mediaRecorder.setVideoEncoder(VideoEncoder.H264);

快乐编码:):D

答案 2 :(得分:1)

以上答案仅在编解码器,帧速率和比特率相同时有效。

等级依赖性(该库几乎在每种情况下都可以使用)

implementation 'com.github.yangjie10930:EpMedia:v0.9.5'

代码

private void mergeVideos() {
        ArrayList<EpVideo> epVideos =  new  ArrayList<>();
        epVideos.add(new EpVideo (file2)); // Video 1
        epVideos.add(new EpVideo (file1)); // Video 2
        EpEditor. OutputOption outputOption =new EpEditor.OutputOption(fileOutput);
        outputOption.setWidth(720);
        outputOption.setHeight(1280);
        outputOption.frameRate = 25 ;
        outputOption.bitRate = 10 ; //Default
        EpEditor.merge(epVideos, outputOption, new  OnEditorListener() {
            @Override
            public  void  onSuccess () {
                Log.d("Status","Success");
            }

            @Override
            public  void  onFailure () {

            }

            @Override
            public  void  onProgress ( float  progress ) {
                // Get processing progress here
                Log.d("Progress",""+progress);
            }
        });

    }