pythonaudio-processing

How to add seconds of silence at the end of a .wav file?


I have 1,440 audio files to feed into a neural network. The problem is that they are not all the same length. I used the answer posted on:

Adding silent frame to wav file using python

but it doesn't seem to work. I wanted to add a few seconds of silence to the end of my files, and then trim them to all be 5 seconds long. Can someone please help me with this?

(I also tried using pysox, but that gives me the This install of SoX cannot process .wav files. error.)

I am using Google Colab for this. The code is:

import wave, os, glob
from pydub import AudioSegment
from pydub.playback import play

path = 'drive/MyDrive/Ravdess/Sad' #This is the folder from my Google Drive which has the audio files
count = 0
for filename in glob.glob(os.path.join(path, '*.wav')):
    w = wave.open(filename, 'r')
    d = w.readframes(w.getnframes())
    frames = w.getnframes()
    rate = w.getframerate()
    duration = frames/float(rate)
    count+=1
    print(filename, "count =", count, "duration = ", duration)
    audio_in_file = filename
    audio_out_file = "out.wav"

    new_duration = duration
    #Only append silence until time = 5 seconds.

    one_sec = AudioSegment.silent(duration=2000) #duration in milliseconds
    song = AudioSegment.from_wav(audio_in_file)
    final_song = one_sec + song
    new_frames = w.getnframes()
    new_rate = w.getframerate()
    new_duration = new_frames/float(rate)
    final_song.export(audio_out_file, format="wav")
    print(final_song, "count =", count, "new duration = ", new_duration)

    w.close()

This gives the output:

drive/MyDrive/Ravdess/Sad/03-01-04-01-02-01-01.wav count = 1 duration =  3.5035

<pydub.audio_segment.AudioSegment object at 0x7fd5b7ca06a0> count = 1 new duration =  3.5035

drive/MyDrive/Ravdess/Sad/03-01-04-01-02-02-01.wav count = 2 duration =  3.370041666666667

<pydub.audio_segment.AudioSegment object at 0x7fd5b7cbc860> count = 2 new duration =  3.370041666666667

... (and so on for all the files)

Solution

  • Since you are already using pydub, I'd do something like this:

    from pydub import AudioSegment
    from pydub.playback import play
    
    input_wav_file   = "/path/to/input.wav"
    output_wav_file  = "/path/to/output.wav"
    target_wav_time  = 5 * 1000 # 5 seconds (or 5000 milliseconds)
    
    original_segment = AudioSegment.from_wav(input_wav_file)
    silence_duration = target_wav_time - len(original_segment)
    silenced_segment = AudioSegment.silent(duration=silence_duration)
    combined_segment = original_segment + silenced_segment
    
    combined_segment.export(output_wav_file, format="wav")