'Unused string raises KeyError

I'm learning python currently and I'm trying to convert .wav files to images of mel spectrograms. When my for loop runs, audio_file raises KeyError and I'm clueless as to why. It happened after I changed my while loop to a for loop.

The line in question: audio_file = '{0}-{1}-{2}.wav'.format(df.Genus[i], df.Specific_epithet[i], df.Recording_ID[i])

The entire file in question:

import librosa
import librosa.display
import numpy as np
import os
from scipy.io.wavfile import read, write
import matplotlib.pyplot as plt

wav_path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..', 'audio', 'wav'))
df = pd.read_csv(os.path.realpath(os.path.join(os.path.dirname(__file__), '..', 'audio', 'metadata.csv')))

for i in os.listdir(wav_path):
    audio_file = '{0}-{1}-{2}.wav'.format(df.Genus[i], df.Specific_epithet[i], df.Recording_ID[i])
    output = "images/mel/{0}/{1}.png".format(df.English_name[i], df.Recording_ID[i])

    try:
        y, sr = librosa.load(wav_path + "\\" + audio_file)
        if os.path.exists(output):
            print("{} already exists. Continuing.".format(output))
            continue
        else:
            pass

    except FileNotFoundError:
        print("{} not found. Continuing.".format(output))
        continue

    mel_s = librosa.feature.melspectrogram(y, sr)
    mel_spectrogram = librosa.power_to_db(mel_s, ref=np.max)
    mel_img = librosa.display.specshow(mel_spectrogram)

    plt.tight_layout()
    try:
        plt.savefig(output)
    except FileNotFoundError:
        print("Creating {}".format(output))
        os.makedirs(output)
        plt.savefig(output)

    print("Conversion of {} successful.".format(output))

    del y, sr, mel_s, mel_spectrogram, mel_img

The lines of error that come up:

  File "c:\Users\elev\Documents\GitHub\CNN-audio-classification\images\audio-to-mel.py", line 13, in <module>
    audio_file = '{0}-{1}-{2}.wav'.format(df.Genus[i], df.Specific_epithet[i], df.Recording_ID[i])
  File "C:\Users\elev\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\series.py", line 958, in __getitem__
    return self._get_value(key)
  File "C:\Users\elev\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\series.py", line 1069, in _get_value
    loc = self.index.get_loc(label)
  File "C:\Users\elev\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\indexes\range.py", line 389, in get_loc
    raise KeyError(key)
KeyError: 'Acrocephalus-arundinaceus-131536.wav'


Solution 1:[1]

I think the error comes on how you are iterating though the wav files.

change this:

for i in os.listdir(wav_path)

for this:

for i, path in enumerate(os.listdir(wav_path))

I understand that you need to get the index of the file i and pass it to the dataframe

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 EnriqueBet