How to split a .wav file into multiple .wav files?

This is a python code snippet that I use for splitting files as per necessity.
I use the pydub library from https://github.com/jiaaro/pydub. You can modify the snippet to suit your requirement.

from pydub import AudioSegment
t1 = t1 * 1000 #Works in milliseconds
t2 = t2 * 1000
newAudio = AudioSegment.from_wav("oldSong.wav")
newAudio = newAudio[t1:t2]
newAudio.export('newSong.wav', format="wav") #Exports to a wav file in the current path.

I've written a class to simplify the whole process. Although it's for wav files.

Here it is:

from pydub import AudioSegment
import math

class SplitWavAudioMubin():
    def __init__(self, folder, filename):
        self.folder = folder
        self.filename = filename
        self.filepath = folder + '\\' + filename
        
        self.audio = AudioSegment.from_wav(self.filepath)
    
    def get_duration(self):
        return self.audio.duration_seconds
    
    def single_split(self, from_min, to_min, split_filename):
        t1 = from_min * 60 * 1000
        t2 = to_min * 60 * 1000
        split_audio = self.audio[t1:t2]
        split_audio.export(self.folder + '\\' + split_filename, format="wav")
        
    def multiple_split(self, min_per_split):
        total_mins = math.ceil(self.get_duration() / 60)
        for i in range(0, total_mins, min_per_split):
            split_fn = str(i) + '_' + self.filename
            self.single_split(i, i+min_per_split, split_fn)
            print(str(i) + ' Done')
            if i == total_mins - min_per_split:
                print('All splited successfully')

Usage

folder = 'F:\\My Audios\\Khaled'
file = 'Khaled Speech.wav'
split_wav = SplitWavAudioMubin(folder, file)
split_wav.multiple_split(min_per_split=1)

That's it! It will split the single wav file into multiple wav files with 1 minute duration each. The last split audio may have less than 1-minute duration ;)

Note: If you're in Mac/Linux, then change \\ to /

Tags:

Python

Audio

Wave