Save manipulated audio files keeping the original name

Asked

Viewed 107 times

0

I’m using an algorithm I found to perform noise cleaning of WAV files, but I need to run this algorithm in more than a thousand files and I need to keep the original name of the file that will be saved in another folder.

I created a directory with the original audios, and ran the algorithm in the loop for below, but I’m having trouble using the original file name when saving.

data_dir = '/Users/Sergio/Desktop/Macuco/WAV1'
audio_files = glob(data_dir + '/*.wav')

len(audio_files)

for file in range(0, len(audio_files), 1):

    data, rate = librosa.load(audio_files[file])
    noisy_part = data[round(len(data)*0.99):len(data)]
    reduced_noise = nr.reduce_noise(audio_clip=data, noise_clip=noisy_part, verbose=True)

    data = np.random.uniform(-1, 1, len(data))
    scaled = np.int16(reduced_noise/np.max(np.abs(data)) * 32768)
    wavfile.write('/Users/Sergio/Desktop/Macuco/WAV1/filtered.wav', rate, scaled)

2 answers

0


The original sound file is being read while the conversion is done, so it is not possible to use the same name for the result. You have to use a different name.

What you can do is generate a temporary file, and as soon as it is fully written, remove the original file and rename the temporary file, so that it gets the same name as the original:

wavfile.write(audio_files[file] + '.tmp', rate, scaled)
os.remove(audio_files[file])
os.rename(audio_files[file] + '.tmp', audio_files[file])
  • I adapted your idea to include the '_filtered' mark next to the original file name, as below. wavfile.write(audio_files[file]. replace('. wav', '_filtered.wav'), rate, Scaled)

0

Or also you could create a directory inside the main folder to store the analyzed files and then save the file already in the final extension in that folder.

I’d just need to add one os.mkdir(f"{data_dir}/WAV_filtrados") at the beginning of your code and instead of saving in the main folder save inside this folder.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.