How to make a video with Python
Upload
your video made with Python at YouTube
I hope you already visited its official website
and read the documenation.
The code snippet we need to write will be just a
few lines of code. Then, execute it at command line.
Let me show you the code first.
# music_video_with_image.py
# 1.
import os, sys
from moviepy.editor import *
# 2.
audio = AudioFileClip(sys.argv[1])
image = ImageClip(sys.argv[2]).set_duration(audio.duration)
video = image.set_audio(audio)
outfile = f"{os.path.splitext(sys.argv[1])[0]}_with_image.mp4" # 3.
video.write_videofile(outfile,
fps=1)
# Use line below if you want to
preserve the name of both files.
# 1. outfile =
f"{os.path.splitext(sys.argv[1])[0]}_with_image_{os.path.splitext(sys.argv[2])[0]}.mp4"
1.
Import os, sys to handle
file names for our preference and to use CLI with arguments. Then, from moviepy.editor import * to use every functions of Moviepy inside
this file.
2.
Write Python code on our
own. They are similar to plain english. You can see that AudioFileClip only extract audio file from the video and you can use it
for image files made from ImageClip.
3.
Use variables for each
files that we prepared above. Then, use Moviepy and Python native API to make a
file with name f"{your_preferred_video_filename_and.ext}.
You may want to know what do sys.argv[1] and
sys.argv[2] mean.
They are just used to indicate arguments that
you will pass in your console later.
You may save it with file name such as music_video_with_image.py for
the next phase.
[Command Line]
$python
music_video_with_single_image.py <video_for_audio> <image>
ex) `$python
music_video_with_image.py audio_from_video.mp4 your_image.jpg`
You almost made it. Type the similar command in
your console with different file names. Then, You will see the process similar
to snippet below and your video file will be ready to use.
$python image_with_audio.py The\
Outfields\ -\ I\ don\'t\ wanna\ lose\ your\ love\ tonight.webm outfiled-yourlove.jpeg
pygame 1.9.4
[MoviePy] >>>>
Building video The Outfields - I don't wanna lose your love
tonight_with_image_outfiled-yourlove.mp4
[MoviePy] Writing audio in The
Outfields - I don't wanna lose your love
tonight_with_image_outfiled-yourloveTEMP_MPY_wvf_snd.mp3
[MoviePy] Done.
[MoviePy] Writing video The
Outfields - I don't wanna lose your love
tonight_with_image_outfiled-yourlove.mp4
[MoviePy] Done.
4. Conclusion
I hope you made it. Just modify some words in examples for your image and video. You may upload the file at YouTube or use it to learn Python.
You can also find some of the example videos
at Steadylearner YouTube. They are made with
almost the same process explained here.
No comments:
Post a Comment