Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
MoviePy
https://github.com/zulko/moviepy
Admin
Video editing with Python
Tokens:
152,714
Snippets:
1,506
Trust Score:
8.8
License:
MIT
Update:
2 months ago
Context
Chat
Benchmark
80.72
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Install MoviePy using pip Source: https://github.com/zulko/moviepy/blob/master/_autodocs/INDEX.md Use pip to install the MoviePy library, which is the primary way to get started with the package. ```bash pip install moviepy ``` -------------------------------- ### Build MoviePy Documentation Source: https://github.com/zulko/moviepy/blob/master/docs/developer_guide/developers_install.md After installing documentation dependencies, run this command to generate the MoviePy documentation. ```bash python setup.py build_docs ``` -------------------------------- ### Example Usage Source: https://github.com/zulko/moviepy/blob/master/docs/reference/reference/moviepy.video.tools.subtitles.SubtitlesClip.md Demonstrates how to create and use a SubtitlesClip with a custom text clip generator and integrate it into a video. ```APIDOC ```python from moviepy.video.tools.subtitles import SubtitlesClip from moviepy.video.io.VideoFileClip import VideoFileClip generator = lambda text: TextClip(text, font='./path/to/font.ttf', font_size=24, color='white') sub = SubtitlesClip("subtitles.srt", make_textclip=generator, encoding='utf-8') myvideo = VideoFileClip("myvideo.avi") final = CompositeVideoClip([clip, subtitles]) final.write_videofile("final.mp4", fps=myvideo.fps) ``` ``` -------------------------------- ### Install FFmpeg (Optional Dependency) Source: https://github.com/zulko/moviepy/blob/master/_autodocs/INDEX.md Install FFmpeg, an optional dependency required for certain video processing functionalities, using the appropriate package manager for your operating system. ```bash brew install ffmpeg ``` ```bash sudo apt-get install ffmpeg ``` ```bash choco install ffmpeg ``` -------------------------------- ### Concatenating and Compositing Audio Clips Source: https://github.com/zulko/moviepy/blob/master/docs/user_guide/compositing.md This example shows how to first concatenate three audio clips to play sequentially and then composite them to play simultaneously at specified start times, including volume adjustment for one clip. ```python """Let's first concatenate (one after the other) then composite (on top of each other) three audio clips.""" from moviepy import AudioFileClip, CompositeAudioClip, concatenate_audioclips # We load all the clips we want to compose clip1 = AudioFileClip("example.wav") clip2 = AudioFileClip("example2.wav") clip3 = AudioFileClip("example3.wav") # All clip will play one after the other concat = concatenate_audioclips([clip1, clip2, clip3]) # We will play clip1, then on top of it clip2 starting at t=5s, # and clip3 on top of both starting t=9s compo = CompositeAudioClip( [ clip1.with_volume_scaled(1.2), clip2.with_start(5), # start at t=5s clip3.with_start(9), ] ) ``` -------------------------------- ### with_start(t, change_end=True) Source: https://github.com/zulko/moviepy/blob/master/_autodocs/01-clip-base.md Returns a copy with the start time set. ```APIDOC ## Method: with_start(t, change_end=True) ### Description Returns a copy with the start time set. ### Signature ```python @convert_parameter_to_seconds(["t"]) @outplace def with_start(self, t, change_end=True) -> Clip ``` ### Parameters - **t** (float, tuple, or str) - Description: New start time in seconds. - **change_end** (bool) - Default: True - Description: If True and clip has duration, end is set to start + duration. ### Returns - A new clip with updated start time. ### Example ```python clip2 = clip.with_start(10) # Clip starts playing at 10 seconds in composition ``` ``` -------------------------------- ### preview(t=0, verbose=False) Source: https://github.com/zulko/moviepy/blob/master/_autodocs/06-audioclip.md Plays a preview of the audio clip using ffplay. You can specify a start time for the preview. ```APIDOC ## preview(t=0, verbose=False) ### Description Preview the audio using ffplay. ### Method Parameters - **t** (float) - Optional - Default: 0 - Start time in seconds. - **verbose** (bool) - Optional - Default: False - If True, print ffplay output. ### Example ```python audio = AudioFileClip('audio.mp3') audio.preview() # Play from start audio.preview(t=30) # Play from 30 seconds audio.close() ``` ``` -------------------------------- ### ImageSequenceClip Usage Examples Source: https://github.com/zulko/moviepy/blob/master/_autodocs/04-videoclip-constructors.md Demonstrates various ways to instantiate an ImageSequenceClip, including from a list of image files, a glob pattern, and with custom durations for individual frames. ```python from moviepy import ImageSequenceClip # From list of files clip = ImageSequenceClip( ['frame1.png', 'frame2.png', 'frame3.png'], fps=30 ) # From glob pattern clip = ImageSequenceClip('frames/frame*.png', fps=24) # Custom durations per frame clip = ImageSequenceClip( ['img1.png', 'img2.png', 'img3.png'], durations=[0.5, 1.0, 0.5] # 0.5s, 1s, 0.5s ) ``` -------------------------------- ### Preview AudioClip with preview (Python) Source: https://github.com/zulko/moviepy/blob/master/_autodocs/06-audioclip.md Plays a preview of the audio clip using ffplay, starting from a specified time. Useful for quick verification. ```python audio = AudioFileClip('audio.mp3') audio.preview() # Play from start audio.preview(t=30) # Play from 30 seconds audio.close() ``` -------------------------------- ### Example: Halving Clip Volume with `with_volume_scaled` in Python Source: https://github.com/zulko/moviepy/blob/master/_autodocs/01-clip-base.md Use this snippet to create a new clip with its audio volume scaled to half the original, demonstrating a basic application of `with_volume_scaled`. ```python quieter = clip.with_volume_scaled(0.5) # Half volume ``` -------------------------------- ### Install MoviePy Testing and Linting Dependencies Source: https://github.com/zulko/moviepy/blob/master/docs/developer_guide/developers_install.md Install the necessary Python packages for running MoviePy tests and linting checks using pip. ```bash (sudo) pip install moviepy[test] ``` ```bash (sudo) pip install moviepy[lint] ``` -------------------------------- ### Install MoviePy Documentation Dependencies Source: https://github.com/zulko/moviepy/blob/master/docs/developer_guide/developers_install.md Install the required Python packages for building MoviePy's documentation using pip. ```bash (sudo) pip install moviepy[doc] ``` -------------------------------- ### Create a SubtitlesClip and Composite with Video Source: https://github.com/zulko/moviepy/blob/master/docs/reference/reference/moviepy.video.tools.subtitles.SubtitlesClip.md This example demonstrates how to create a SubtitlesClip from an SRT file, customize text rendering with a TextClip generator, and composite it with an existing VideoFileClip before writing the final video. ```python from moviepy.video.tools.subtitles import SubtitlesClip from moviepy.video.io.VideoFileClip import VideoFileClip generator = lambda text: TextClip(text, font='./path/to/font.ttf', font_size=24, color='white') sub = SubtitlesClip("subtitles.srt", make_textclip=generator, encoding='utf-8') myvideo = VideoFileClip("myvideo.avi") final = CompositeVideoClip([clip, subtitles]) final.write_videofile("final.mp4", fps=myvideo.fps) ``` -------------------------------- ### Creating TextClips with MoviePy Source: https://github.com/zulko/moviepy/blob/master/_autodocs/04-videoclip-constructors.md These examples demonstrate how to create `TextClip` instances with different styles, including simple text, text with outlines, and multi-line text with custom sizing. ```python from moviepy import TextClip # Simple text txt = TextClip( text='Hello World', font='Arial.ttf', fontsize=50, color='white' ).with_duration(3) ``` ```python # Styled text with outline txt = TextClip( text='MoviePy', fontsize=60, color=(255, 100, 100), stroke_color='black', stroke_width=2, font='Courier New' ).with_duration(5) ``` ```python # Multi-line with custom size txt = TextClip( text='This is a long text\nthat wraps', fontsize=40, color='yellow', size=(400, 200), method='caption' ).with_duration(5) ``` -------------------------------- ### Create a video with text overlay using MoviePy Source: https://github.com/zulko/moviepy/blob/master/_autodocs/INDEX.md This example demonstrates how to load a video, add a text overlay, compose the elements, and export the final video file using MoviePy's core classes. ```python from moviepy import VideoFileClip, TextClip, CompositeVideoClip # Load video clip = VideoFileClip('input.mp4').subclipped(0, 20) # Create text overlay txt = TextClip( text='Hello!', fontsize=50, color='white' ).with_duration(clip.duration).with_position('center') # Compose and export final = CompositeVideoClip([clip, txt]) final.write_videofile('output.mp4') clip.close() ``` -------------------------------- ### Install MoviePy with Development Dependencies (Bash) Source: https://github.com/zulko/moviepy/blob/master/CONTRIBUTING.md Installs the MoviePy library in editable mode within a virtual environment, including all optional development dependencies for documentation, testing, and linting. ```bash $ pip install -e ".[optional,doc,test,lint]" ``` -------------------------------- ### Start MoviePy Docker Container and Run Script Interactively Source: https://github.com/zulko/moviepy/blob/master/docs/getting_started/docker.md Start an interactive bash session in the MoviePy container, then manually execute a Python script. ```bash docker run -it moviepy bash python myscript.py ``` -------------------------------- ### Positioning Text and Image Clips on a Video Source: https://github.com/zulko/moviepy/blob/master/docs/user_guide/compositing.md This example demonstrates how to layer and position multiple text and image clips onto a background video using `with_position()`. It showcases defining positions with relative percentages, absolute pixel coordinates, and a time-dependent function for dynamic movement. ```python """Let's position some text and images on a video.""" from moviepy import CompositeVideoClip, ImageClip, TextClip, VideoFileClip # We load all the clips we want to compose background = VideoFileClip("example2.mp4").subclipped(0, 2) title = TextClip( "./example.ttf", text="Big Buck Bunny", font_size=80, color="#fff", text_align="center", duration=1, ) author = TextClip( "./example.ttf", text="Blender Foundation", font_size=40, color="#fff", text_align="center", duration=1, ) copyright = TextClip( "./example.ttf", text="© CC BY 3.0", font_size=20, color="#fff", text_align="center", duration=1, ) logo = ImageClip("./example2.png", duration=1).resized(height=50) # We want our title to be at the center horizontaly and start at 25% # of the video verticaly. We can set as "center", "left", "right", # "top" and "bottom", and % relative from the clip size title = title.with_position(("center", 0.25), relative=True) # We want the author to be in the center, 30px under the title # We can set as pixels top = background.h * 0.25 + title.h + 30 left = (background.w - author.w) / 2 author = author.with_position((left, top)) # We want the copyright to be 30px before bottom copyright = copyright.with_position(("center", background.h - copyright.h - 30)) # Finally, we want the logo to be in the center, but to drop as time pass # We can do so by setting position as a function that take time as argument, # a lot like frame_function top = (background.h - logo.h) / 2 logo = logo.with_position(lambda t: ("center", top + t * 30)) # We write the result final_clip = CompositeVideoClip([background, title, author, copyright, logo]) final_clip.write_videofile("final_clip.mp4") ``` -------------------------------- ### Process Video with Multiple MoviePy Effects in Python Source: https://github.com/zulko/moviepy/blob/master/_autodocs/08-effects.md Example demonstrating how to load a video, apply a sequence of resize, fade-in, and fade-out effects, and then write the processed video to a file. ```python from moviepy import VideoFileClip, vfx clip = VideoFileClip('video.mp4') # Apply multiple effects processed = clip.with_effects([ vfx.Resize(height=720), vfx.FadeIn(1), vfx.FadeOut(1) ]) processed.write_videofile('output.mp4') clip.close() ``` -------------------------------- ### Configure Pre-commit Hooks (Bash) Source: https://github.com/zulko/moviepy/blob/master/CONTRIBUTING.md Installs the pre-commit hooks to automatically run code quality checks (black, flake8, isort) before each commit. ```bash $ pre-commit install ``` -------------------------------- ### CompositeAudioClip.starts Source: https://github.com/zulko/moviepy/blob/master/docs/reference/reference/moviepy.audio.AudioClip.CompositeAudioClip.md This property returns the starting times for all individual audio clips within the composite audio clip. It allows users to understand when each component clip begins playing within the overall composition. ```APIDOC ## CompositeAudioClip.starts Property ### Description Returns starting times for all clips in the composition. ### Signature CompositeAudioClip.starts ### Returns Starting times for all clips in the composition. ``` -------------------------------- ### Applying Image Transformation and Previewing Clip Source: https://github.com/zulko/moviepy/blob/master/docs/getting_started/moviepy_10_minutes.md This snippet demonstrates applying a custom image transformation (like a sepia filter) to a video clip using `image_transform`, then previewing the result. It also shows the initial setup for composing a final video clip. ```python # Because final result can be > 255, we limit the result to range [0, 255] sepia_image = np.clip(sepia_image, 0, 255) # Convert the image back to uint8 format, because we need integer not float sepia_image = sepia_image.astype(np.uint8) return sepia_image # Now, we simply apply the filter to our clip by calling image_transform, which will call our filter on every frame rambo_clip = rambo_clip.image_transform(sepia_filter) # Let's see how our filter look rambo_clip.preview(fps=10) ################## # CLIP RENDERING # ################## # Everything is good and ready, we can finally render our clip into a file final_clip = CompositeVideoClip( [ ``` -------------------------------- ### Splitting Images with color_split in Python Source: https://github.com/zulko/moviepy/blob/master/docs/reference/reference/moviepy.video.tools.drawing.color_split.md These examples demonstrate how to use `color_split` to divide an image horizontally, vertically, or along an arbitrary line, applying different colors to the resulting regions. ```python size = [200, 200] # an image with all pixels with x<50 =0, the others =1 color_split(size, x=50, color_1=0, color_2=1) # an image with all pixels with y<50 red, the others green color_split(size, x=50, color_1=[255, 0, 0], color_2=[0, 255, 0]) # An image split along an arbitrary line (see below) color_split(size, p1=[20, 50], p2=[25, 70], color_1=0, color_2=1) ``` -------------------------------- ### with_start(t, change_end=True) Source: https://github.com/zulko/moviepy/blob/master/docs/reference/reference/moviepy.Clip.Clip.md Returns a copy of the clip, with the `start` attribute set to `t`, which can be expressed in seconds (15.35), in (min, sec), in (hour, min, sec), or as a string: ‘01:03:05.35’. These changes are also applied to the `audio` and `mask` clips of the current clip, if they exist. ```APIDOC ## with_start(t, change_end=True) ### Description Returns a copy of the clip, with the `start` attribute set to `t`, which can be expressed in seconds (15.35), in (min, sec), in (hour, min, sec), or as a string: ‘01:03:05.35’. These changes are also applied to the `audio` and `mask` clips of the current clip, if they exist. ### Method with_start ### Parameters #### Function Parameters - **t** (float or tuple or str) - Required - New `start` attribute value for the clip. - **change_end** (bool) - Optional - Indicates if the `end` attribute value must be changed accordingly, if possible. If `change_end=True` and the clip has a `duration` attribute, the `end` attribute of the clip will be updated to `start + duration`. If `change_end=False` and the clip has a `end` attribute, the `duration` attribute of the clip will be updated to `end - start`. ``` -------------------------------- ### Example creditfile Format for CreditsClip Source: https://github.com/zulko/moviepy/blob/master/docs/reference/reference/moviepy.video.tools.credits.CreditsClip.md This snippet shows the expected text file format for the `creditfile` parameter of `CreditsClip`, including comments, blank line directives, and job-name pairs. ```python # This is a comment # The next line says : leave 4 blank lines .blank 4 ..Executive Story Editor MARCEL DURAND ..Associate Producers MARTIN MARCEL DIDIER MARTIN ..Music Supervisor JEAN DIDIER ``` -------------------------------- ### Example Output Format of CreditsClip Source: https://github.com/zulko/moviepy/blob/master/docs/reference/reference/moviepy.video.tools.credits.CreditsClip.md This snippet illustrates the visual layout of the generated credits, showing the alignment of job titles and names as an `ImageClip` instance. ```text Executive Story Editor MARCEL DURAND Associate Producers MARTIN MARCEL DIDIER MARTIN Music Supervisor JEAN DIDIER ``` -------------------------------- ### Write Matching Frames as GIFs with FramesMatches in Python Source: https://github.com/zulko/moviepy/blob/master/docs/reference/reference/moviepy.video.tools.cuts.FramesMatches.md This example shows how to use the write_gifs method to extract identified matching frames from a clip and save them as individual GIF files in a specified directory. Ensure the output directory exists before calling write_gifs. ```python import os from pprint import pprint from moviepy import * from moviepy.video.tools.cuts import FramesMatches ch_clip = VideoFileClip("media/chaplin.mp4").subclipped(1, 4) clip = concatenate_videoclips([ch_clip.time_mirror(), ch_clip]) result = FramesMatches.from_clip(clip, 10, 3).select_scenes( 1, 2, nomatch_threshold=0, ) os.mkdir("foo") result.write_gifs(clip, "foo") # MoviePy - Building file foo/00000100_00000400.gif with imageio. # MoviePy - Building file foo/00000115_00000384.gif with imageio. # MoviePy - Building file foo/00000128_00000372.gif with imageio. # MoviePy - Building file foo/00000140_00000360.gif with imageio. ``` -------------------------------- ### initialize(start_time=0) Source: https://github.com/zulko/moviepy/blob/master/docs/reference/reference/moviepy.audio.io.readers.FFMPEG_AudioReader.md Opens the file, creates the pipe. ```APIDOC ## Method: initialize(start_time=0) ### Description Opens the file, creates the pipe. ### Parameters - **start_time** (int) - The starting time for initialization (default is 0). ``` -------------------------------- ### Video with Audio Mixing and Text Overlay in MoviePy Source: https://github.com/zulko/moviepy/blob/master/_autodocs/10-complete-examples.md This example demonstrates how to combine a video with background music, adjust audio properties like volume and fade, and add a title text overlay. ```python from moviepy import VideoFileClip, AudioFileClip, TextClip, CompositeVideoClip, afx # Load video and audio video = VideoFileClip('video.mp4') background_music = AudioFileClip('music.mp3') # Reduce music volume and fade out music = background_music.with_duration(video.duration).with_effects([ afx.AudioFadeOut(1) # Fade out last second ]) # Set video audio to music (video's original audio is replaced) video = video.with_audio(music) # Add title text title = TextClip( text='My Video', fontsize=60, color='white' ).with_duration(3).with_position('center') # Composite final = CompositeVideoClip([video, title]) final.write_videofile('final.mp4') video.close() music.close() background_music.close() ``` -------------------------------- ### initialize Source: https://github.com/zulko/moviepy/blob/master/docs/reference/reference/moviepy.video.io.ffmpeg_reader.FFMPEG_VideoReader.md Opens the video file and creates the ffmpeg pipe. It also sets the internal position (`self.pos`) to the appropriate value, pre-reading the first frame if `start_time` is 0. ```APIDOC ## Method: initialize(start_time=0) ### Description Opens the file, creates the pipe. Sets self.pos to the appropriate value (1 if start_time == 0 because it pre-reads the first frame). ### Parameters - **start_time** (float) - Optional - Default: `0`. The time in seconds from which to start reading the video. ``` -------------------------------- ### Get MoviePy Version in Python Source: https://github.com/zulko/moviepy/blob/master/_autodocs/09-utilities.md Use this snippet to programmatically retrieve the installed MoviePy library version. ```python from moviepy import __version__ print(__version__) # e.g., "2.2.0" ``` -------------------------------- ### Lazy Evaluation in MoviePy Source: https://github.com/zulko/moviepy/blob/master/_autodocs/INDEX.md MoviePy computes frames only when requested, saving memory. This example shows how to get a specific frame from a video clip. ```python clip = VideoFileClip('huge_video.mp4') frame = clip.get_frame(5) # Only computes frame at 5s ``` -------------------------------- ### Loading Video Files with VideoFileClip Source: https://github.com/zulko/moviepy/blob/master/_autodocs/04-videoclip-constructors.md Demonstrates how to load video files using `VideoFileClip`, including basic instantiation, applying constructor options, and ensuring proper resource cleanup with a context manager or manual `close()`. ```python from moviepy import VideoFileClip # Basic loading clip = VideoFileClip('video.mp4') print(f"Duration: {clip.duration}s, Size: {clip.size}, FPS: {clip.fps}") # With options clip = VideoFileClip( 'video.mp4', target_resolution=(640, 480), audio=False # Skip audio loading ) # With context manager for automatic cleanup with VideoFileClip('video.mp4') as clip: clip.save_frame('frame.png', t=5) # Auto-closed clip.close() # Manual cleanup ``` -------------------------------- ### Stacking Video Clips with CompositeVideoClip in Python Source: https://github.com/zulko/moviepy/blob/master/docs/user_guide/compositing.md Demonstrates how to layer multiple video clips using CompositeVideoClip, with later clips appearing on top of earlier ones. This example shows three clips stacked simultaneously. ```python """Let's stack three video clips on top of each other with CompositeVideoClip.""" from moviepy import VideoFileClip, CompositeVideoClip # We load all the clips we want to compose clip1 = VideoFileClip("example.mp4") clip2 = VideoFileClip("example2.mp4").subclipped(0, 1) clip3 = VideoFileClip("example.mp4") # We concatenate them and write theme stacked on top of each other, # with clip3 over clip2 over clip1 final_clip = CompositeVideoClip([clip1, clip2, clip3]) final_clip.write_videofile("final_clip.mp4") ``` -------------------------------- ### Creating and Exporting a CompositeVideoClip Source: https://github.com/zulko/moviepy/blob/master/_autodocs/07-composite.md Demonstrates how to load video and image clips, then combine them into a `CompositeVideoClip` using different constructor options for size, background color, and background clip usage. Finally, it shows how to write the composite to a file. ```python from moviepy import VideoFileClip, TextClip, CompositeVideoClip # Load clips bg = VideoFileClip('background.mp4') logo = ImageClip('logo.png').with_duration(5).with_position('topright') txt = TextClip('Credits', fontsize=40, color='white').with_duration(5) # Composite with specific size and background final = CompositeVideoClip( [bg, logo, txt], size=(1280, 720), bg_color=(0, 0, 0) ) # Composite with first clip as background clips = [bg, logo, txt] final = CompositeVideoClip(clips, use_bgclip=True) final.write_videofile('output.mp4') final.close() ``` -------------------------------- ### Iterate Frames and Get Max Red Value (Python) Source: https://github.com/zulko/moviepy/blob/master/docs/reference/reference/moviepy.Clip.Clip.md Use `iter_frames()` to process video frames individually. This example calculates the maximum red channel value on the first line of each frame from a `VideoFileClip`. ```python # prints the maximum of red that is contained # on the first line of each frame of the clip. from moviepy import VideoFileClip myclip = VideoFileClip('myvideo.mp4') print([frame[0,:,0].max() for frame in myclip.iter_frames()]) ``` -------------------------------- ### Install MoviePy using pip Source: https://github.com/zulko/moviepy/blob/master/docs/getting_started/install.md Installs the MoviePy library using the pip package manager from the command line, optionally with sudo for system-wide installation. ```bash $ (sudo) pip install moviepy ``` -------------------------------- ### Clip.subclipped(start, end) Source: https://github.com/zulko/moviepy/blob/master/_autodocs/11-api-summary.md Returns a subclip of the current clip, defined by start and end times. ```APIDOC ## Clip.subclipped ### Description Returns a subclip of the current clip, defined by start and end times. ### Signature subclipped(start, end) ### Parameters #### Positional/Keyword Parameters - **start** (float) - Start time in seconds. - **end** (float) - End time in seconds. ### Returns Clip ``` -------------------------------- ### Create and render TextClip with custom font, size, and color (Python) Source: https://github.com/zulko/moviepy/blob/master/docs/user_guide/loading.md Create a TextClip from a string or file, configuring its appearance with parameters like font, size, color, and background. Remember to set duration and FPS before rendering to a video file. ```python from moviepy import TextClip font = "./example.ttf" # First we use as string and let system autocalculate clip dimensions to fit the text # we set clip duration to 2 secs, if we do not, it got an infinite duration txt_clip1 = TextClip( font=font, text="Hello World !", font_size=30, color="#FF0000", # Red bg_color="#FFFFFF", duration=2, ) # This time we load text from a file, we set a fixed size for clip and let the system find best font size, # allowing for line breaking txt_clip2 = TextClip( font=font, filename="./example.txt", size=(500, 200), bg_color="#FFFFFF", method="caption", color=(0, 0, 255, 127), ) # Blue with 50% transparency # we set duration, because by default image clip are infinite, and we cannot render infinite txt_clip2 = txt_clip2.with_duration(2) # ImageClip have no FPS either, so we must defined it txt_clip1.write_videofile("result1.mp4", fps=24) txt_clip2.write_videofile("result2.mp4", fps=24) ``` -------------------------------- ### Crop a rectangle with a starting x-coordinate and width Source: https://github.com/zulko/moviepy/blob/master/docs/reference/reference/moviepy.video.fx.Crop.md Define the crop region by its starting x-coordinate (x1) and its total width. ```python >>> Crop(x1=10, width=200) ``` -------------------------------- ### Verify FFmpeg Installation with MoviePy Source: https://github.com/zulko/moviepy/blob/master/_autodocs/INDEX.md Use `config.check()` to confirm if FFmpeg is installed and accessible by MoviePy, which is crucial for video processing. ```python from moviepy import config config.check() # Verify ffmpeg is installed and accessible ``` -------------------------------- ### CompositeAudioClip.__init__ Source: https://github.com/zulko/moviepy/blob/master/_autodocs/06-audioclip.md Initializes a new `CompositeAudioClip` instance by mixing multiple audio clips together. ```APIDOC ## Class: CompositeAudioClip ### Constructor def __init__(self, clips) ### Description Initializes a new CompositeAudioClip instance by mixing multiple audio clips together. ### Parameters #### Arguments - **clips** (list) - Required - List of AudioClip instances. ### Returns A new CompositeAudioClip instance. ### Usage Example ```python from moviepy import AudioFileClip, CompositeAudioClip music = AudioFileClip('music.mp3') voice = AudioFileClip('voice.wav').with_start(5) mixed = CompositeAudioClip([music, voice]) mixed.write_audiofile('mixed.mp3') mixed.close() ``` ``` -------------------------------- ### Setting a Clip's Start Time in Python Source: https://github.com/zulko/moviepy/blob/master/_autodocs/01-clip-base.md Returns a copy of the clip with its start time adjusted within a composition. If `change_end` is True, the end time is also adjusted to maintain duration. ```python clip2 = clip.with_start(10) ``` -------------------------------- ### Controlling Clip Start and End Times in MoviePy Composition Source: https://github.com/zulko/moviepy/blob/master/docs/user_guide/compositing.md Illustrates how to adjust the playback start and end times of individual clips within a CompositeVideoClip using `with_end()`, `with_start()`, and `with_duration()` methods to create a sequential composition. ```python from moviepy import VideoFileClip, CompositeVideoClip # We load all the clips we want to compose clip1 = VideoFileClip("example.mp4") clip2 = VideoFileClip("example2.mp4").subclipped(0, 1) clip3 = VideoFileClip("example3.mp4") # We want to stop clip1 after 1s clip1 = clip1.with_end(1) # We want to play clip2 after 1.5s clip2 = clip2.with_start(1.5) # We want to play clip3 at the end of clip2, and so for 3 seconds only # Some times its more practical to modify the duration of a clip instead # of his end clip3 = clip3.with_start(clip2.end).with_duration(1) # We write the result final_clip = CompositeVideoClip([clip1, clip2, clip3]) final_clip.write_videofile("final_clip.mp4") ``` -------------------------------- ### Applying AudioDelay Effect to Audio Clips (Python) Source: https://github.com/zulko/moviepy/blob/master/docs/reference/reference/moviepy.audio.fx.AudioDelay.md Demonstrates applying the `AudioDelay` effect to both file-based audio clips and programmatically generated audio clips. It shows how to configure offset, repetitions, and decay parameters. ```python from moviepy import * videoclip = AudioFileClip('myaudio.wav').with_effects([ afx.AudioDelay(offset=.2, n_repeats=10, decayment=.2) ]) ``` ```python # stereo A note frame_function = lambda t: np.array( [np.sin(440 * 2 * np.pi * t), np.sin(880 * 2 * np.pi * t)] ).T clip = AudioClip(frame_function=frame_function, duration=0.1, fps=44100) clip = clip.with_effects([afx.AudioDelay(offset=.2, n_repeats=11, decay=0)]) ``` -------------------------------- ### VideoClip.preview(t=0, interactive=True) Source: https://github.com/zulko/moviepy/blob/master/_autodocs/11-api-summary.md Previews the video clip, starting from a specified time, with optional interactivity. ```APIDOC ## VideoClip.preview ### Description Previews the video clip, starting from a specified time, with optional interactivity. ### Signature preview(t=0, interactive=True) ### Parameters #### Positional/Keyword Parameters - **t** (float) - Start time in seconds (default is 0). - **interactive** (bool) - If True, allows interactive control during preview. ### Returns None ``` -------------------------------- ### Clip.with_start(t, change_end=True) Source: https://github.com/zulko/moviepy/blob/master/_autodocs/11-api-summary.md Sets the start time of the clip. Optionally adjusts the end time to maintain duration. ```APIDOC ## Clip.with_start ### Description Sets the start time of the clip. Optionally adjusts the end time to maintain duration. ### Signature with_start(t, change_end=True) ### Parameters #### Positional/Keyword Parameters - **t** (float) - New start time. - **change_end** (bool) - If True, end time changes; otherwise, duration changes. ### Returns Clip ``` -------------------------------- ### Create a Copy of an Effect in Python Source: https://github.com/zulko/moviepy/blob/master/_autodocs/08-effects.md Demonstrates how to create a shallow copy of an effect using the `copy()` method before application. ```python effect = vfx.Resize(0.5) effect_copy = effect.copy() ``` -------------------------------- ### MultiplyVolume Source: https://github.com/zulko/moviepy/blob/master/_autodocs/08-effects.md Multiplies audio volume by a specified factor, with optional start and end times for partial application. ```APIDOC ## MultiplyVolume ### Description Multiplies audio volume by a factor. ### Class Signature ```python @dataclass class MultiplyVolume(Effect): factor: float start_time: float = None end_time: float = None ``` ### Parameters - **factor** (float) - Required - Volume multiplier (2 = double, 0.5 = half). - **start_time** (float) - Optional - Optional start time for fade-in effect. - **end_time** (float) - Optional - Optional end time for fade-out effect. ### Example ```python clip.with_effects([afx.MultiplyVolume(0.5)]) # Half volume clip.with_effects([afx.MultiplyVolume(0)]) # Silence clip.with_effects([afx.MultiplyVolume(0, start_time=2, end_time=3)]) # Silence from 2-3s ``` ``` -------------------------------- ### Configure FFmpeg/FFplay Paths using Environment Variables Source: https://github.com/zulko/moviepy/blob/master/_autodocs/09-utilities.md Set `FFMPEG_BINARY` and `FFPLAY_BINARY` environment variables to specify custom paths for FFmpeg and FFplay executables, either in the shell or a `.env` file. ```bash # Set in .env file or shell export FFMPEG_BINARY="/usr/local/bin/ffmpeg" export FFPLAY_BINARY="/usr/local/bin/ffplay" python my_script.py ``` ```env FFMPEG_BINARY=/usr/local/bin/ffmpeg FFPLAY_BINARY=/usr/local/bin/ffplay ``` -------------------------------- ### Set FFmpeg Binary Path Source: https://github.com/zulko/moviepy/blob/master/_autodocs/INDEX.md Configure the `FFMPEG_BINARY` environment variable or create a `.env` file to specify the FFmpeg executable's location, resolving 'FFmpeg Not Found' errors. ```bash export FFMPEG_BINARY=/path/to/ffmpeg # Or create .env file: # FFMPEG_BINARY=/path/to/ffmpeg ``` -------------------------------- ### Run MoviePy Unit Tests Source: https://github.com/zulko/moviepy/blob/master/docs/developer_guide/developers_install.md Execute the MoviePy test suite using pytest after installing the testing dependencies. ```bash python -m pytest ``` -------------------------------- ### is_playing(t) Source: https://github.com/zulko/moviepy/blob/master/_autodocs/02-clip-methods-continued.md Returns whether a given time `t` (or times) falls within the clip's active [start, end] range. ```APIDOC ## is_playing(t) ### Description Returns whether time `t` is within the clip's [start, end] range. ### Parameters - **t** (float, tuple, str, or numpy array) - Time(s) to check in seconds. ### Returns - Boolean (single time) or boolean array (if `t` is array). ### Example ```python clip = clip.with_start(5).with_end(15) print(clip.is_playing(10)) # True print(clip.is_playing(20)) # False # With array import numpy as np times = np.array([3, 8, 20]) playing = clip.is_playing(times) # [False, True, False] ``` ``` -------------------------------- ### moviepy.video.io.VideoFileClip.VideoFileClip(filename, decode_file=False, has_mask=False, audio=True, audio_buffersize=200000, target_resolution=None, resize_algorithm='bicubic', audio_fps=44100, audio_nbytes=2, fps_source='fps', pixel_format=None, is_mask=False, audio_stream_index=0) Source: https://github.com/zulko/moviepy/blob/master/docs/reference/reference/moviepy.video.io.VideoFileClip.VideoFileClip.md Initializes a VideoFileClip object from a movie file, allowing various configurations for loading video and audio streams. ```APIDOC ## Class: VideoFileClip ### Description A video clip originating from a movie file. ### Signature `*class* moviepy.video.io.VideoFileClip.VideoFileClip(filename, decode_file=False, has_mask=False, audio=True, audio_buffersize=200000, target_resolution=None, resize_algorithm='bicubic', audio_fps=44100, audio_nbytes=2, fps_source='fps', pixel_format=None, is_mask=False, audio_stream_index=0)` ### Parameters - **filename** (string or path-like object) - The name of the video file. It can have any extension supported by ffmpeg: .ogv, .mp4, .mpeg, .avi, .mov etc. - **has_mask** (bool) - Set this to 'True' if there is a mask included in the videofile. - **audio** (bool) - Set to False if the clip doesn't have any audio or if you do not wish to read the audio. - **target_resolution** (tuple) - Set to (desired_width, desired_height) to have ffmpeg resize the frames before returning them. If either dimension is None, the frames are resized by keeping the existing aspect ratio. - **resize_algorithm** (string) - The algorithm used for resizing. Default: "bicubic", other popular options include "bilinear" and "fast_bilinear". - **fps_source** (string) - The fps value to collect from the metadata. Set by default to 'fps', but can be set to 'tbr'. - **pixel_format** (string) - Optional: Pixel format for the video to read. If is not specified 'rgb24' will be used as the default format unless `has_mask` is set as `True`, then 'rgba' will be used. - **is_mask** (bool) - True if the clip is going to be used as a mask. - **audio_stream_index** (int) - The index of the audio stream to read from the file. ### Example ```python clip = VideoFileClip("myHolidays.mp4") clip.close() with VideoFileClip("myMaskVideo.avi") as clip2: pass # Implicit close called by context manager. ``` ``` -------------------------------- ### Changing Video Speed to 0.5x in MoviePy Source: https://github.com/zulko/moviepy/blob/master/_autodocs/INDEX.md Adjust the playback speed of a video clip. This example halves the speed of the clip. ```python slow = clip.with_speed_scaled(0.5) # Half speed ``` -------------------------------- ### VideoFileClip Constructor Source: https://github.com/zulko/moviepy/blob/master/_autodocs/04-videoclip-constructors.md Initializes a VideoFileClip object from a video file, allowing for various configurations like audio loading, resolution resizing, and pixel format. ```APIDOC ## Class: VideoFileClip ### Description Initializes a VideoFileClip object from a video file, allowing for various configurations like audio loading, resolution resizing, and pixel format. ### Constructor Signature ```python def __init__( self, filename, decode_file=False, has_mask=False, audio=True, audio_buffersize=200000, target_resolution=None, resize_algorithm='bicubic', audio_fps=44100, audio_nbytes=2, fps_source='fps', pixel_format=None, is_mask=False, audio_stream_index=0 ) ``` ### Parameters - **filename** (str or path-like) - Required - Path to video file (any format supported by ffmpeg: .mp4, .avi, .mov, .mkv, etc.). - **decode_file** (bool) - Optional (Default: False) - If True, fully decode video into memory first. - **has_mask** (bool) - Optional (Default: False) - If True, last channel of video is the transparency mask. - **audio** (bool) - Optional (Default: True) - If True, load audio track if present. - **audio_buffersize** (int) - Optional (Default: 200000) - Buffer size for audio reading. - **target_resolution** (tuple | None) - Optional (Default: None) - Resize frames to (width, height). If dimension is None, maintain aspect ratio. - **resize_algorithm** (str) - Optional (Default: 'bicubic') - Ffmpeg resize algorithm ('bilinear', 'fast_bilinear', 'bicubic', etc.). - **audio_fps** (int) - Optional (Default: 44100) - Sample rate for audio in Hz. - **audio_nbytes** (int) - Optional (Default: 2) - Bytes per audio sample (1, 2, or 4). - **fps_source** (str) - Optional (Default: 'fps') - Metadata field for fps ('fps' or 'tbr'). Use 'tbr' if fps incorrect. - **pixel_format** (str | None) - Optional (Default: None) - Ffmpeg pixel format ('rgb24', 'rgba', etc.). Auto-selected if None. - **is_mask** (bool) - Optional (Default: False) - If True, clip is used as a mask. - **audio_stream_index** (int) - Optional (Default: 0) - Index of audio stream to read if multiple streams exist. ### Attributes - **filename** (str) - Path to the original video file. - **fps** (float) - Frames per second from file metadata. - **size** (tuple) - (width, height) in pixels. - **duration** (float) - Duration in seconds. - **rotation** (int) - Video rotation in degrees (0, 90, 180, 270). - **audio** (AudioClip | None) - Audio track if loaded. ### Usage Example ```python from moviepy import VideoFileClip # Basic loading clip = VideoFileClip('video.mp4') print(f"Duration: {clip.duration}s, Size: {clip.size}, FPS: {clip.fps}") # With options clip = VideoFileClip( 'video.mp4', target_resolution=(640, 480), audio=False # Skip audio loading ) # With context manager for automatic cleanup with VideoFileClip('video.mp4') as clip: clip.save_frame('frame.png', t=5) # Auto-closed clip.close() # Manual cleanup ``` ``` -------------------------------- ### Changing Video Speed to 2x in MoviePy Source: https://github.com/zulko/moviepy/blob/master/_autodocs/INDEX.md Adjust the playback speed of a video clip. This example doubles the speed of the clip. ```python fast = clip.with_speed_scaled(2) # 2x speed ``` -------------------------------- ### moviepy.video.tools.cuts.FramesMatch Constructor Source: https://github.com/zulko/moviepy/blob/master/docs/reference/reference/moviepy.video.tools.cuts.FramesMatch.md Initializes a FramesMatch object to define a set of frames based on start time, end time, and distance constraints. ```APIDOC ## Class: `moviepy.video.tools.cuts.FramesMatch` ### Description Frames match inside a set of frames. ### Constructor `FramesMatch(start_time, end_time, min_distance, max_distance)` ### Parameters - **start_time** (`float`) - Starting time. - **end_time** (`float`) - End time. - **min_distance** (`float`) - Lower bound on the distance between the first and last frames. - **max_distance** (`float`) - Upper bound on the distance between the first and last frames. ``` -------------------------------- ### Initialize CompositeAudioClip Source: https://github.com/zulko/moviepy/blob/master/_autodocs/06-audioclip.md Initializes a `CompositeAudioClip` instance, accepting a list of `AudioClip` objects to be mixed. ```python def __init__(self, clips) ``` -------------------------------- ### Resizing a Video Clip in MoviePy Source: https://github.com/zulko/moviepy/blob/master/_autodocs/INDEX.md Resize a video clip to a specific dimension. This example resizes the video to a height of 720 pixels. ```python resized = clip.with_effects([vfx.Resize(height=720)]) ``` -------------------------------- ### Create and Close an AudioFileClip in Python Source: https://github.com/zulko/moviepy/blob/master/docs/reference/reference/moviepy.audio.io.AudioFileClip.AudioFileClip.md Initializes an AudioFileClip from a WAV file and demonstrates the essential `close()` method to release system resources, preventing file locks and subprocesses from lingering. ```python snd = AudioFileClip("song.wav") snd.close() ``` -------------------------------- ### Initialize DataVideoClip Source: https://github.com/zulko/moviepy/blob/master/_autodocs/04-videoclip-constructors.md Initializes a `DataVideoClip` from a function that generates frames and specifies the clip's size. Use this for creating clips from raw data. ```python def __init__(self, frame_function, size, duration=None, fps=None, is_mask=False) ``` -------------------------------- ### Simulating a Coin Flip World with UpdatedVideoClip Source: https://github.com/zulko/moviepy/blob/master/docs/user_guide/loading.md This example demonstrates how to create a custom 'world' object (`CoinFlipWorld`) that manages its own state and time (`clip_t`), and then use it with `UpdatedVideoClip` to generate a video. The `update()` method advances the world state, and `to_frame()` renders the current state into a video frame. ```python import random import numpy as np from moviepy import UpdatedVideoClip class CoinFlipWorld: """A simulation of coin flipping. Imagine we want to make a video that become more and more red as we repeat same face on coinflip in a row because coinflip are done in real time, we need to wait until a winning row is done to be able to make the next frame. This is a world simulating that. Sorry, it's hard to come up with examples... """ def __init__(self, fps): """ FPS is usefull because we must increment clip_t by 1/FPS to have UpdatedVideoClip run with a certain FPS """ self.clip_t = 0 self.win_strike = 0 self.reset = False self.fps = fps def update(self): if self.reset: self.win_strike = 0 self.reset = False print("strike : {}, clip_t : {}".format(self.win_strike, self.clip_t)) print(self.win_strike) # 0 tails, 1 heads, this is our simulation of coinflip choice = random.randint(0, 1) face = random.randint(0, 1) # We win, we increment our serie and retry if choice == face: self.win_strike += 1 return # Different face, we increment clip_t and set reset so we will reset on next update. # We don't reset immediately because we will need current state to make frame self.reset = True self.clip_t += 1 / self.fps def to_frame(self): """Return a frame of a 200x100 image with red more or less intense based on number of victories in a row.""" red_intensity = 255 * (self.win_strike / 10) red_intensity = min(red_intensity, 255) # A 200x100 image with red more or less intense based on number of victories in a row return np.full((100, 200, 3), (red_intensity, 0, 0), dtype=np.uint8) world = CoinFlipWorld(fps=5) myclip = UpdatedVideoClip(world=world, duration=10) # We will set FPS to same as world, if we was to use a different FPS, # the lowest from world.fps and our write_videofile fps param # will be the real visible fps myclip.write_videofile("result.mp4", fps=5) ``` -------------------------------- ### Extract File Extension with find_extension (Python) Source: https://github.com/zulko/moviepy/blob/master/_autodocs/09-utilities.md Demonstrates how to use `find_extension` to get the extension of a file, returning it in lowercase without the leading dot. ```python from moviepy.tools import find_extension find_extension('video.mp4') # 'mp4' find_extension('image.PNG') # 'png' ```