Skip to content
Advertisement

How can i split an Audio file into multiple audio wav files from folder

I have a folder where i have about 2000 audio files in wav format with different time intervals, say some are in 30 sec some 40 and i want to split all of them using python, i tried pydub and different libraries and all of them working for 1 file only, i want to split those using a loop with simple code in python.

Sample code:

from pydub import AudioSegment 
from pydub.utils import make_chunks 

myaudio = AudioSegment.from_file("a0007.wav", "wav") 
chunk_length_ms = 8000 # pydub calculates in millisec 
chunks = make_chunks(myaudio,chunk_length_ms) #Make chunks of one sec 
for i, chunk in enumerate(chunks): 
    chunk_name = "{0}.wav".format(i) 
    print ("exporting", chunk_name) 
    chunk.export(chunk_name, format="wav") 

The above code is working for one file whereas i need it to take files from folder and split all of them

Advertisement

Answer

You have to get all the file names in your directory and then iterate for all file names.

You can use os module to get list of all the files in the current directory.

from pydub import AudioSegment 
from pydub.utils import make_chunks
import os

def process_sudio(file_name):
    myaudio = AudioSegment.from_file(file_name, "wav") 
    chunk_length_ms = 8000 # pydub calculates in millisec 
    chunks = make_chunks(myaudio,chunk_length_ms) #Make chunks of one sec 
    for i, chunk in enumerate(chunks): 
        chunk_name = './chunked/' + file_name + "_{0}.wav".format(i) 
        print ("exporting", chunk_name) 
        chunk.export(chunk_name, format="wav") 

all_file_names = os.listdir()
try:
    os.makedirs('chunked') # creating a folder named chunked
except:
    pass
for each_file in all_file_names:
    if ('.wav' in each_file):
        process_sudio(each_file)
User contributions licensed under: CC BY-SA
11 People found this is helpful
Advertisement