Video editing with Python
Added audio tests, fixed a few bugs, neater code
Tom Burrows89a2a7884f21
diff --git a/moviepy/Clip.py b/moviepy/Clip.pyindex 4e72f5d7..9a1fc657 100644--- a/moviepy/Clip.py+++ b/moviepy/Clip.py@@ -335,7 +335,7 @@ class Clip:# is the whole list of t outside the clip ?tmin, tmax = t.min(), t.max()- if (self.end is not None) and (tmin >= self.end) :+ if (self.end is not None) and (tmin >= self.end):return Falseif tmax < self.start:@@ -349,9 +349,8 @@ class Clip:else:- return( (t >= self.start) and- ((self.end is None) or (t < self.end) ) )-+ return((t >= self.start) and+ ((self.end is None) or (t < self.end)))@convert_to_seconds(['t_start', 't_end'])@@ -385,9 +384,9 @@ class Clip:t_start = self.duration + t_start # Remember t_start is negativeif (self.duration is not None) and (t_start > self.duration):- raise ValueError("t_start (%.02f) "% t_start +- "should be smaller than the clip's "+- "duration (%.02f)."% self.duration)+ raise ValueError("t_start (%.02f) " % t_start ++ "should be smaller than the clip's " ++ "duration (%.02f)." % self.duration)newclip = self.fl_time(lambda t: t + t_start, apply_to=[])@@ -395,7 +394,7 @@ class Clip:t_end = self.duration- elif (t_end is not None) and (t_end<0):+ elif (t_end is not None) and (t_end < 0):if self.duration is None:diff --git a/moviepy/audio/AudioClip.py b/moviepy/audio/AudioClip.pyindex 95f02972..883bff88 100644--- a/moviepy/audio/AudioClip.py+++ b/moviepy/audio/AudioClip.py@@ -34,16 +34,20 @@ class AudioClip(Clip):Examples---------- >>> # Plays the note A (a sine wave of frequency 404HZ)+ >>> # Plays the note A (a sine wave of frequency 440HZ)>>> import numpy as np- >>> make_frame = lambda t : 2*[ np.sin(404 * 2 * np.pi * t) ]+ >>> make_frame = lambda t: 2*[ np.sin(440 * 2 * np.pi * t) ]>>> clip = AudioClip(make_frame, duration=5)>>> clip.preview()"""- def __init__(self, make_frame=None, duration=None):+ def __init__(self, make_frame=None, duration=None, fps=None):Clip.__init__(self)++ if fps is not None:+ self.fps = fps+if make_frame is not None:self.make_frame = make_frameframe0 = self.get_frame(0)@@ -142,7 +146,7 @@ class AudioClip(Clip):return maxi@requires_duration- def write_audiofile(self, filename, fps=44100, nbytes=2, buffersize=2000,+ def write_audiofile(self, filename, fps=None, nbytes=2, buffersize=2000,codec=None, bitrate=None, ffmpeg_params=None,write_logfile=False, verbose=True, progress_bar=True):""" Writes an audio file from the AudioClip.@@ -155,7 +159,8 @@ class AudioClip(Clip):Name of the output filefps- Frames per second+ Frames per second. If not set, it will try default to self.fps if+ already set, otherwise it will default to 44100nbytesSample width (set to 2 for 16-bit sound, 4 for 32-bit sound)@@ -186,6 +191,11 @@ class AudioClip(Clip):Boolean indicating whether to show the progress bar."""+ if not fps:+ if not self.fps:+ fps = 44100+ else:+ fps = self.fpsif codec is None:name, ext = os.path.splitext(os.path.basename(filename))@@ -194,7 +204,7 @@ class AudioClip(Clip):except KeyError:raise ValueError("MoviePy couldn't find the codec associated ""with the filename. Provide the 'codec' "- "parameter in write_videofile.")+ "parameter in write_audiofile.")return ffmpeg_audiowrite(self, filename, fps, nbytes, buffersize,codec=codec, bitrate=bitrate,@@ -302,7 +312,19 @@ class CompositeAudioClip(AudioClip):def concatenate_audioclips(clips):+ """+ The clip with the highest FPS will be the FPS of the result clip.+ """durations = [c.duration for c in clips]tt = np.cumsum([0]+durations) # start times, and end time.newclips = [c.set_start(t) for c, t in zip(clips, tt)]- return CompositeAudioClip(newclips).set_duration(tt[-1])++ result = CompositeAudioClip(newclips).set_duration(tt[-1])++ fpss = [c.fps for c in clips if hasattr(c, 'fps') and c.fps is not None]+ if len(fpss) == 0:+ result.fps = None+ else:+ result.fps = max(fpss)++ return resultdiff --git a/moviepy/audio/io/AudioFileClip.py b/moviepy/audio/io/AudioFileClip.pyindex 34b5e970..74410c55 100644--- a/moviepy/audio/io/AudioFileClip.py+++ b/moviepy/audio/io/AudioFileClip.py@@ -25,12 +25,7 @@ class AudioFileClip(AudioClip):buffersize:Size to load in memory (in number of frames)-- temp_wav:- Name for the temporary wav file in case conversion is required.- If not provided, the default will be filename.wav with some prefix.- If the temp_wav already exists it will not be rewritten.-+Attributes------------@@ -59,7 +54,7 @@ class AudioFileClip(AudioClip):>>> snd = AudioFileClip("song.wav")>>> snd.close()- >>> snd = AudioFileClip("song.mp3", fps = 44100, bitrate=3000)+ >>> snd = AudioFileClip("song.mp3", fps = 44100)>>> second_reader = snd.coreader()>>> second_reader.close()>>> snd.close()diff --git a/moviepy/audio/io/ffmpeg_audiowriter.py b/moviepy/audio/io/ffmpeg_audiowriter.pyindex 334704cf..bfde5920 100644--- a/moviepy/audio/io/ffmpeg_audiowriter.py+++ b/moviepy/audio/io/ffmpeg_audiowriter.py@@ -55,7 +55,7 @@ class FFMPEG_AudioWriter:'-i', '-']+ (['-vn'] if input_video is None else ["-i", input_video, '-vcodec', 'copy'])+ ['-acodec', codec]- + ['-ar', "%d"%fps_input]+ + ['-ar', "%d" % fps_input]+ ['-strict', '-2'] # needed to support codec 'aac'+ (['-ab', bitrate] if (bitrate is not None) else [])+ (ffmpeg_params if ffmpeg_params else [])@@ -166,7 +166,7 @@ def ffmpeg_audiowrite(clip, filename, fps, nbytes, buffersize,for chunk in clip.iter_chunks(chunksize=buffersize,quantize=True,- nbytes= nbytes, fps=fps,+ nbytes=nbytes, fps=fps,progress_bar=progress_bar):writer.write_frames(chunk)diff --git a/moviepy/audio/io/preview.py b/moviepy/audio/io/preview.pyindex ad489b93..26c3e3ae 100644--- a/moviepy/audio/io/preview.py+++ b/moviepy/audio/io/preview.py@@ -10,8 +10,8 @@ pg.display.set_caption('MoviePy')@requires_duration-def preview(clip, fps=22050, buffersize=4000, nbytes= 2,- audioFlag=None, videoFlag=None):+def preview(clip, fps=22050, buffersize=4000, nbytes=2, audioFlag=None,+ videoFlag=None):"""Plays the sound clip with pygame.@@ -45,8 +45,8 @@ def preview(clip, fps=22050, buffersize=4000, nbytes= 2,pg.mixer.init(fps, -8 * nbytes, clip.nchannels, 1024)totalsize = int(fps*clip.duration)pospos = np.array(list(range(0, totalsize, buffersize))+[totalsize])- tt = (1.0/fps)*np.arange(pospos[0],pospos[1])- sndarray = clip.to_soundarray(tt,nbytes=nbytes, quantize=True)+ tt = (1.0/fps)*np.arange(pospos[0], pospos[1])+ sndarray = clip.to_soundarray(tt, nbytes=nbytes, quantize=True)chunk = pg.sndarray.make_sound(sndarray)if (audioFlag is not None) and (videoFlag is not None):@@ -54,13 +54,13 @@ def preview(clip, fps=22050, buffersize=4000, nbytes= 2,videoFlag.wait()channel = chunk.play()- for i in range(1,len(pospos)-1):- tt = (1.0/fps)*np.arange(pospos[i],pospos[i+1])- sndarray = clip.to_soundarray(tt,nbytes=nbytes, quantize=True)+ for i in range(1, len(pospos)-1):+ tt = (1.0/fps)*np.arange(pospos[i], pospos[i+1])+ sndarray = clip.to_soundarray(tt, nbytes=nbytes, quantize=True)chunk = pg.sndarray.make_sound(sndarray)while channel.get_queue():time.sleep(0.003)- if (videoFlag!= None):+ if videoFlag is not None:if not videoFlag.is_set():channel.stop()del channeldiff --git a/moviepy/audio/io/readers.py b/moviepy/audio/io/readers.pyindex 6d85a689..853b4be1 100644--- a/moviepy/audio/io/readers.py+++ b/moviepy/audio/io/readers.py@@ -161,8 +161,8 @@ class FFMPEG_AudioReader:# elements of t that are actually in the range of the# audio file.in_time = (tt>=0) & (tt < self.duration)-- # Check that the requested time is in the valid range++ # Check that the requested time is in the valid rangeif not in_time.any():raise IOError("Error in file %s, "%(self.filename)+"Accessing time t=%.02f-%.02f seconds, "%(tt[0], tt[-1])+diff --git a/moviepy/editor.py b/moviepy/editor.pyindex f8a91408..5ea3b37c 100644--- a/moviepy/editor.py+++ b/moviepy/editor.py@@ -70,7 +70,7 @@ for method in ["vfx.speedx"]:- exec("VideoClip.%s = %s"%( method.split('.')[1], method))+ exec("VideoClip.%s = %s" % (method.split('.')[1], method))for method in ["afx.audio_fadein",@@ -80,7 +80,7 @@ for method in ["afx.audio_fadein","afx.volumex"]:- exec("AudioClip.%s = %s"%( method.split('.')[1], method))+ exec("AudioClip.%s = %s" % (method.split('.')[1], method))# adds easy ipython integration@@ -98,6 +98,7 @@ except ImportError:def preview(self, *args, **kwargs):"""NOT AVAILABLE : clip.preview requires Pygame installed."""raise ImportError("clip.preview requires Pygame installed")+def show(self, *args, **kwargs):"""NOT AVAILABLE : clip.show requires Pygame installed."""raise ImportError("clip.show requires Pygame installed")diff --git a/tests/test_AudioClips.py b/tests/test_AudioClips.pynew file mode 100644index 00000000..b21a7921--- /dev/null+++ b/tests/test_AudioClips.py@@ -0,0 +1,75 @@+# -*- coding: utf-8 -*-+"""Image sequencing clip tests meant to be run with pytest."""+import os+import sys++from numpy import sin, pi+import pytest++from moviepy.audio.io.AudioFileClip import AudioFileClip+from moviepy.audio.AudioClip import AudioClip, concatenate_audioclips, CompositeAudioClip++sys.path.append("tests")+import download_media+from test_helper import TMP_DIR+++def test_audio_coreader():+ sound = AudioFileClip("media/crunching.mp3")+ sound = sound.subclip(1, 4)+ sound2 = sound.coreader()+ sound2.write_audiofile(os.path.join(TMP_DIR, "coreader.mp3"))+++def test_audioclip():+ make_frame = lambda t: [sin(440 * 2 * pi * t)]+ clip = AudioClip(make_frame, duration=2, fps=22050)+ clip.write_audiofile(os.path.join(TMP_DIR, "audioclip.mp3"))+++def test_audioclip_concat():+ make_frame_440 = lambda t: [sin(440 * 2 * pi * t)]+ make_frame_880 = lambda t: [sin(880 * 2 * pi * t)]++ clip1 = AudioClip(make_frame_440, duration=1, fps=44100)+ clip2 = AudioClip(make_frame_880, duration=2, fps=22050)++ concat_clip = concatenate_audioclips((clip1, clip2))+ # concatenate_audioclips should return a clip with an fps of the greatest+ # fps passed into it+ assert concat_clip.fps == 44100++ return+ # Does run without errors, but the length of the audio is way to long,+ # so it takes ages to run.+ concat_clip.write_audiofile(os.path.join(TMP_DIR, "concat_audioclip.mp3"))+++def test_audioclip_with_file_concat():+ make_frame_440 = lambda t: [sin(440 * 2 * pi * t)]+ clip1 = AudioClip(make_frame_440, duration=1, fps=44100)++ clip2 = AudioFileClip("media/crunching.mp3")++ concat_clip = concatenate_audioclips((clip1, clip2))++ return+ # Fails with strange error+ # "ValueError: operands could not be broadcast together with+ # shapes (1993,2) (1993,1993)1+ concat_clip.write_audiofile(os.path.join(TMP_DIR, "concat_clip_with_file_audio.mp3"))+++def test_audiofileclip_concat():+ sound = AudioFileClip("media/crunching.mp3")+ sound = sound.subclip(1, 4)++ # Checks it works with videos as well+ sound2 = AudioFileClip("media/big_buck_bunny_432_433.webm")+ concat = concatenate_audioclips((sound, sound2))++ concat.write_audiofile(os.path.join(TMP_DIR, "concat_audio_file.mp3"))+++if __name__ == "__main__":+ pytest.main()