Skip to content

Instantly share code, notes, and snippets.

@guiszk
Created December 20, 2021 03:23
Show Gist options
  • Save guiszk/c55aec0aace55c15482ac8c12a385fc7 to your computer and use it in GitHub Desktop.
Save guiszk/c55aec0aace55c15482ac8c12a385fc7 to your computer and use it in GitHub Desktop.
Split audio files in equal parts with pydub
import os, sys
import pydub
import numpy as np
if(len(sys.argv) != 3):
print(f"{sys.argv[0]} <audio file> <number of parts>")
sys.exit(1)
filename = sys.argv[1]
numparts = int(sys.argv[2])
filepath = os.path.abspath(filename)
filebase = os.path.basename(filename)
fileext = filename.split('.')[-1]
nameonly = '_'.join(filebase.split(' ')).split('.')[-2]
track = pydub.AudioSegment.from_file(filename, fileext)
track_Value = np.array(track.get_array_of_samples())
#tlength = track.duration_seconds*1000
tlength = round(track.duration_seconds*1000+1)
ranges = [(i*tlength/numparts, (i+1)*tlength/numparts) for i in range(numparts)]
os.mkdir(nameonly)
num = 0
for x, y in ranges:
x = int(x)*100
y = int(y)*100
new_file=track_Value[x:y]
song = pydub.AudioSegment(new_file.tobytes(), frame_rate=track.frame_rate*2,sample_width=track.sample_width,channels=1)
song.export(f'{nameonly}/{nameonly}_{num}.mp3', format="mp3")
num += 1
#song.export(str(x) + "-" + str(y) +".mp3", format="mp3")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment