Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
300 views
in Technique[技术] by (71.8m points)

python - 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

question from:https://stackoverflow.com/questions/65857983/how-can-i-split-an-audio-file-into-multiple-audio-wav-files-from-folder

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...