pythonaudioaudio-processing

How to make length of two audios of same name equal?


I have two audios in different directories but having same name say a.wav But both the audios having different length, i want to make there length same and i'm not getting how do i do that.

Please find below the audio configurations.

Channels       : 1
Sample Rate    : 16000
Precision      : 16-bit
Duration       : 00:00:15.66 = 250586 samples ~ 1174.62 CDDA sectors
File Size      : 501k
Bit Rate       : 256k
Sample Encoding: 16-bit Signed Integer PCM

The other audio file configuration:

Input File     : 'a.wav'
Channels       : 1
Sample Rate    : 16000
Precision      : 16-bit
Duration       : 00:00:15.19 = 243040 samples ~ 1139.25 CDDA sectors
File Size      : 486k
Bit Rate       : 256k
Sample Encoding: 16-bit Signed Integer PCM

Solution

  • The padding or cropping techniques may causing damage to data and if you don't want that, you have to change the length to avoid damaging the features of the audio file.

    You can use this code :

    import librosa as sib
    from PIL import Image
    import numpy as np
    import soundfile as sd 
    
    path_file = 'file.wave'
    sound , sample = sib.load(path_file,sr= None)
    new_len = sample * 2 
    #the number (2) above represent the desired length of file in seconds
    intermediate = Image.fromarray(np.array([sound]))
    new_sound = np.array(intermediate.resize((new_len,1)))[0]
    sd.write('new_audio.wav' , new_sound, sample)
    

    Of course, if this code is for one file, you have to apply it twice to solve your problem. Don't forget to change the path and the output file name in the sd.write function.