Skip to content

Instantly share code, notes, and snippets.

@mzmttks
Created June 15, 2021 03:19
Show Gist options
  • Save mzmttks/3669824c0734e2143df15ede619f0dff to your computer and use it in GitHub Desktop.
Save mzmttks/3669824c0734e2143df15ede619f0dff to your computer and use it in GitHub Desktop.
Audio file separator
"""
Audio file separator
This script splits an audio file into a given length of video files.
1. Split an input file into a given length of .wav files
2. Combine the .wav file with a given video file using FFmpeg
You can use this script to prepare for audio psychological experiments.
(c) T.Mizumoto
"""
import pathlib
import subprocess
import argparse
import pydub
import pydub.utils
import numpy
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"file",
help="Input audio file"
)
parser.add_argument(
"--videofile", default="noaudio.mp4",
help="A silent video file to combine with audio chunks."
)
parser.add_argument(
"--chunk_length", default=60, type=int,
help="duration of the audio file"
)
args = parser.parse_args()
# parse audio file
input_file = pathlib.Path(args.file)
sound = pydub.AudioSegment.from_file(file=args.file)
samples = numpy.array(sound.get_array_of_samples())
nsamples = len(samples)
chunk_size = args.chunk_length * sound.frame_rate
# prepare a folder to store the chunks
folder = pathlib.Path(input_file.with_suffix(""))
folder.mkdir(exist_ok=True)
# Calculate start and end samples, splits, and converts into a video
for index, start in enumerate(range(0, nsamples, chunk_size)):
end = start + chunk_size
print(start, end, sound[start:end])
filename = folder / ("%05d.wav" % index)
sound[start:end].export(filename, format="wav")
subprocess.call(
"ffmpeg -i %s -i %s -y %s.mp4" % (
args.videofile, filename, filename.with_suffix("")
), shell=True
)
filename.unlink()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment