0

I want to convert a gif to a video with ffmpeg in python and add sound to the video. Afterwards I want to merge the video with another video. I'm able to run the shell codes with os.system() in python, however I would like to avoid writing multiple files during my steps.

Is there a way to save the ffmpeg output in a variable and work with the variable instead of writing multiple files for each step? I want only to write my final file which should be a merged video file, containing the video and the sound from video1 and another video2. I've found some ways like the subprocess library, but unfortunately was not able to code my desired output.

Here is the code I use and which works for converting a gif to mp4 and add sound. But as described I need to write 2 different files.

GIF to video:

os.system(f'ffmpeg -i {PATH_TO_GIF} -movflags faststart -pix_fmt yuv420p -vf "scale=trunc(iw/2)*2:trunc(ih/2)*2" video.mp4')

Add sound to video:

os.system(f"ffmpeg -i video.mp4 -i {PATH_TO_SOUNDFILE} -map 0:v -map 1:a -c:v copy -shortest video_with_sound.mp4")
rtn17
  • 11
  • 2

2 Answers2

0

maybe something like

ffmpeg -i i.gif -i 1.wav -map 0:v -map 1:a -movflags faststart -pix_fmt yuv420p -vf "scale=trunc(iw/2)*2:trunc(ih/2)*2" -shortest vid.mp4

Or maybe somehow possible with a two-pass conversion and dev null. As a last resort, it is always possible to execute several commands at once and remove unnecessary‍♂️

Alex
  • 3
  • 2
  • Thanks for your answer! I also had this in my mind but was curious if there is a more efficient way without writing multiple files and deleting the unnecessary ones afterwards. – rtn17 Oct 04 '21 at 16:45
0

Combined command:

os.system(f'ffmpeg -i {PATH_TO_GIF} -i {PATH_TO_SOUNDFILE} -map 0:v -map 1:a -vf "scale=trunc(iw/2)*2:trunc(ih/2)*2,format=yuv420p" -movflags +faststart -shortest video_with_sound.mp4')

Optional: You can add -c:a copy to stream copy the audio if {PATH_TO_SOUNDFILE} is MP4/M4A/AAC.

llogan
  • 121,796
  • 28
  • 232
  • 243
  • Thanks for your quick response. At the end I want to merge the video_with_sound.mp4 with another video2.mp4 to generate my final output. Is there a way to do so before writing the video_with_sound.mp4? – rtn17 Oct 04 '21 at 16:39
  • @rtn17 "merge" is ambiguous. Do you mean to concatenate where one video plays right after the other? – llogan Oct 04 '21 at 16:41
  • Yes that's what I meant with merge. – rtn17 Oct 04 '21 at 16:43
  • @rtn17 See [How to concatenate videos in ffmpeg with different attributes?](https://stackoverflow.com/a/57367243/) – llogan Oct 04 '21 at 16:44