Video editing with Python
Ensure that AudioFileClip does not change the audio (#1108)
Yun Wang (Maigo)8df153f0b278
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex da54ae50..a070ee07 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -48,6 +48,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- `vfx.even_size` previously created clips with odd sizes [#1124]- `IndexError` in `vfx.freeze`, `vfx.time_mirror` and `vfx.time_symmetrize` [#1124]- Using `rotate()` with a `ColorClip` no longer crashes [#1139]+- `AudioFileClip` would not generate audio identical to the original file [#1108]## [v1.0.2](https://github.com/zulko/moviepy/tree/v1.0.2) (2020-03-26)diff --git a/moviepy/audio/AudioClip.py b/moviepy/audio/AudioClip.pyindex a98f5e93..689f876f 100644--- a/moviepy/audio/AudioClip.py+++ b/moviepy/audio/AudioClip.py@@ -272,8 +272,8 @@ class AudioArrayClip(AudioClip):is a list of the form sin(t) """if isinstance(t, np.ndarray):- array_inds = (self.fps * t).astype(int)- in_array = (array_inds > 0) & (array_inds < len(self.array))+ array_inds = np.round(self.fps * t).astype(int)+ in_array = (array_inds >= 0) & (array_inds < len(self.array))result = np.zeros((len(t), 2))result[in_array] = self.array[array_inds[in_array]]return resultdiff --git a/moviepy/audio/io/readers.py b/moviepy/audio/io/readers.pyindex abefd4f2..58042a8d 100644--- a/moviepy/audio/io/readers.py+++ b/moviepy/audio/io/readers.py@@ -133,6 +133,11 @@ class FFMPEG_AudioReader:result = (1.0 * result / 2 ** (8 * self.nbytes - 1)).reshape((int(len(result) / self.nchannels), self.nchannels))++ # Pad the read chunk with zeros when there isn't enough audio+ # left to read, so the buffer is always at full length.+ pad = np.zeros((chunksize - len(result), self.nchannels), dtype=result.dtype)+ result = np.concatenate([result, pad])# self.proc.stdout.flush()self.pos = self.pos + chunksizereturn result@@ -175,7 +180,7 @@ class FFMPEG_AudioReader:raise IOError("Error in file %s, " % (self.filename)+ "Accessing time t=%.02f-%.02f seconds, " % (tt[0], tt[-1])- + "with clip duration=%d seconds, " % self.duration+ + "with clip duration=%f seconds, " % self.duration)# The np.round in the next line is super-important.@@ -191,8 +196,6 @@ class FFMPEG_AudioReader:try:result = np.zeros((len(tt), self.nchannels))indices = frames - self.buffer_startframe- if len(self.buffer) < self.buffersize // 2:- indices = indices - (self.buffersize // 2 - len(self.buffer) + 1)result[in_time] = self.buffer[indices]return result@@ -236,8 +239,8 @@ class FFMPEG_AudioReader:if self.buffer is not None:current_f_end = self.buffer_startframe + self.buffersizeif new_bufferstart < current_f_end < new_bufferstart + self.buffersize:- # We already have one bit of what must be read- conserved = current_f_end - new_bufferstart + 1+ # We already have part of what must be read+ conserved = current_f_end - new_bufferstartchunksize = self.buffersize - conservedarray = self.read_chunk(chunksize)self.buffer = np.vstack([self.buffer[-conserved:], array])diff --git a/tests/test_AudioClips.py b/tests/test_AudioClips.pyindex 88f646e7..a1dbd934 100644--- a/tests/test_AudioClips.py+++ b/tests/test_AudioClips.py@@ -4,9 +4,15 @@ import osimport sysimport pytest+import numpy as npfrom numpy import pi, sin-from moviepy.audio.AudioClip import AudioClip, concatenate_audioclips+from moviepy.audio.AudioClip import (+ AudioArrayClip,+ AudioClip,+ CompositeAudioClip,+ concatenate_audioclips,+)from moviepy.audio.io.AudioFileClip import AudioFileClipfrom tests.test_helper import TMP_DIR@@ -31,6 +37,25 @@ def test_audioclip():clip.write_audiofile(os.path.join(TMP_DIR, "audioclip.mp3"))+def test_audioclip_io():+ # Generate a random audio clip of 4.989 seconds at 44100 Hz,+ # and save it to a file.+ input_array = np.random.random((220000, 2)) * 1.98 - 0.99+ clip = AudioArrayClip(input_array, fps=44100)+ clip.write_audiofile(os.path.join(TMP_DIR, "random.wav"))+ # Load the clip.+ # The loaded clip will be slightly longer because the duration is rounded+ # up to 4.99 seconds.+ # Verify that the extra frames are all zero, and the remainder is identical+ # to the original signal.+ clip = AudioFileClip(os.path.join(TMP_DIR, "random.wav"))+ output_array = clip.to_soundarray()+ np.testing.assert_array_almost_equal(+ output_array[: len(input_array)], input_array, decimal=4+ )+ assert (output_array[len(input_array) :] == 0).all()++def test_audioclip_concat():make_frame_440 = lambda t: [sin(440 * 2 * pi * t)]make_frame_880 = lambda t: [sin(880 * 2 * pi * t)]