How to concatenate two MP4 files using FFmpeg?

后端 未结 22 3068
遇见更好的自我
遇见更好的自我 2020-11-22 02:32

I\'m trying to concatenate two mp4 files using ffmpeg. I need this to be an automatic process hence why I chose ffmpeg. I\'m converting the two files into .ts files and th

22条回答
  •  梦如初夏
    2020-11-22 03:31

    Here 2 pure bash solutions using only ffmpeg and not using

    • an intermediary file
    • perl, python nor javascript

    One-liner solution using ls

    ls video1.mp4 video2.mp4 | while read line; do echo file \'$line\'; done | ffmpeg -protocol_whitelist file,pipe -f concat -i - -c copy output.mp4
    

    Function which takes 0 or 2+ arguments

    #######################################
    # Merge mp4 files into one output mp4 file
    # usage:
    #   mergemp4 #merges all mp4 in current directory
    #   mergemp4 video1.mp4 video2.mp4
    #   mergemp4 video1.mp4 video2.mp4 [ video3.mp4 ...] output.mp4 
    #######################################
    function mergemp4() {
      if [ $# = 1 ]; then return; fi
    
      outputfile="output.mp4"
    
      #if no arguments we take all mp4 in current directory as array
      if [ $# = 0 ]; then inputfiles=($(ls -1v *.mp4)); fi
      if [ $# = 2 ]; then inputfiles=($1 $2); fi  
      if [ $# -ge 3 ]; then
        outputfile=${@: -1} # Get the last argument
        inputfiles=(${@:1:$# - 1}) # Get all arguments besides last one as array
      fi
      
      # -y: automatically overwrite output file if exists
      # -loglevel quiet: disable ffmpeg logs
      ffmpeg -y \
      -loglevel quiet \
      -f concat \
      -safe 0 \
      -i <(for f in $inputfiles; do echo "file '$PWD/$f'"; done) \
      -c copy $outputfile
    
      if test -f "$outputfile"; then echo "$outputfile created"; fi
    }
    

    Note: had tried some solutions in this thread and none satisfied me

提交回复
热议问题