简体   繁体   中英

Merge/Concatenate two videos with c#

I am trying to merge two videos with one another, below is a sample code i am trying to make it work

    FileStream fs = new FileStream(@"C:\Users\test\Downloads\m.mp4", FileMode.Append);
    
    //m1,m2,m3 are video mp4 files on my disk
    var bytes = System.IO.File.ReadAllBytes(@"C:\Users\test\Downloads\m1.mp4");
    fs.Write(bytes,0 ,bytes.Length);
                    
    fs.Close();
    
    FileStream fs1 = new FileStream(@"C:\Users\test\Downloads\m.mp4", FileMode.Append);
    
    //m1,m2 are video mp4 files on my disk
    var bytes1 = System.IO.File.ReadAllBytes(@"C:\Users\test\Downloads\m2.mp4");
    fs1.Write(bytes1,0 ,bytes1.Length);
            
    fs1.Close();

Now what happens is that the new video has the size of the two videos combined but only shows the first video and has the duration of only the first video. How can i fix that?

The MP4 format should be seen as something like a zip-file: one file as a bag holding multiple other files (like the audio stream and the video stream).

When the file is opened, the header or index is read in order to know which content is to expect. If you concat a second MP4 after the first MP4 content then that content will never be found since it isnt in the first header. This is fundamentaly different then lets say a text-file as then there is only just content.

So what you want is a library that opens up the MP4 and reads it's index and then be able to add content to that package and update the index.

A quick look on google brought me to VisioForge but i'm sure that there are some free libraries to be found as well.

A few possible solutions:

  1. Check this answer which uses FFmpeg - https://stackoverflow.com/a/41387530/4000335 This can be called from C# Process.Start eg this answer https://stackoverflow.com/a/1733516/4000335
  2. NReco VideoConverter FFmpeg wrapper NuGet library (has a free license option), check this answer for concatenate example - https://stackoverflow.com/a/23054427/4000335

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM