Home>

When processing audio files with python, I want to read the files in bulk instead of reading them one by one.

If one by one

sound = AudioSegment.from_file ("001.wav", format = "wav")


I can read it with
On the other hand, I would like you to teach me how to read multiple files (for example, if there are three files 001.wav, 002.wav, 003.wav) in order from 001.wav.

I'm new to python and I'm sorry for the basic question. I look forward to working with you.

* By the way, I would like to load and execute the following programs in the order of 001.wav, 002.wav, 003.wav.
(It is a process to cut the audio from one audio file with a blank and write it to a file for each cut audio.)

from pydub import AudioSegment
from pydub.silence import split_on_silence

#Wav file data acquisition
sound = AudioSegment.from_file ("001.wav", format = "wav")
# wav data division (separate by silence)
chunks = split_on_silence (sound, min_silence_len = 1000, silence_thresh = -50, keep_silence = 400)

# Output to a file for each divided data
for i, chunk in enumerate (chunks):
    chunk.export ("out" + str (i + 1) + ".wav", format = "wav")
  • Answer # 1

    As an alternative, how about specifying the file name you want to read in the argument of the python script?

    split_wav.py

    from pydub import AudioSegment
    from pydub.silence import split_on_silence
    import sys
    #Specify the file name from the argument
    if len (sys.argv)! = 2:
        print ('usage:% s<filename>'% sys.argv [0])
        sys.exit ()
    input_file = sys.argv [1]
    #Wav file data acquisition
    sound = AudioSegment.from_file (input_file, format = "wav")
    # wav data division (separate by silence)
    chunks = split_on_silence (sound, min_silence_len = 1000, silence_thresh = -50, keep_silence = 400)
    # Output to a file for each divided data
    # Output as out_<input_file (excluding .wav)>_<numerical value>.wav so that the file name is not covered
    for i, chunk in enumerate (chunks):
        # chunk.export ("out" + str (i + 1) + ".wav", format = "wav")
        chunk.export ("out_" + input_file.split ('.') [0] + str (i + 1) + ".wav", format = "wav")

    Execution example

    $python3 split_wave.py 001.wav

    If you want to execute multiple files at once, you can pass a list of files as a shell script or batch.

    Example. For shell

    $cat files.txt
    001.wav
    002.wav
    003.wav
    $
    $for file in `cat files.txt`;do python3 split_wav.py $file;done;
    # The following is executed in order
    # python3 split_wav.py 001.wav
    # python3 split_wav.py 002.wav
    # python3 split_wav.py 003.wav

  • Answer # 2

    sound1 = AudioSegment.from_file ("001.wav", format = "wav")
    sound2 = AudioSegment.from_file ("002.wav", format = "wav")
    sound3 = AudioSegment.from_file ("003.wav", format = "wav")

    Is it no good?