def extract_snr(audio, sr=None):
    """Extract Signal-to-Noise Ratio for a given audio."""
    if sr != None:
        audio, _ = librosa.load(audio, sr=sr)
    else:
        audio, sr = librosa.load(audio, sr=sr)
    faxis, ps = sig.periodogram(
        audio, fs=sr, window=("kaiser", 38)
    )  # get periodogram, parametrized like in matlab
    fundBin = np.argmax(
        ps
    )  # estimate fundamental at maximum amplitude, get the bin number
    fundIndizes = getIndizesAroundPeak(
        ps, fundBin
    )  # get bin numbers around fundamental peak
    fundFrequency = faxis[fundBin]  # frequency of fundamental

    nHarmonics = 18
    harmonicFs = getHarmonics(
        fundFrequency, sr, nHarmonics=nHarmonics, aliased=True
    )  # get harmonic frequencies

    harmonicBorders = np.zeros([2, nHarmonics], dtype=np.int16).T
    fullHarmonicBins = np.array([], dtype=np.int16)
    fullHarmonicBinList = []
    harmPeakFreqs = []
    harmPeaks = []
    for i, harmonic in enumerate(harmonicFs):
        searcharea = 0.1 * fundFrequency
        estimation = harmonic

        binNum, freq = getPeakInArea(ps, faxis, estimation, searcharea)
        harmPeakFreqs.append(freq)
        harmPeaks.append(ps[binNum])
        allBins = getIndizesAroundPeak(ps, binNum, searchWidth=1000)
        fullHarmonicBins = np.append(fullHarmonicBins, allBins)
        fullHarmonicBinList.append(allBins)
        harmonicBorders[i, :] = [allBins[0], allBins[-1]]

    fundIndizes.sort()
    pFund = bandpower(ps[fundIndizes[0] : fundIndizes[-1]])  # get power of fundamental

    noisePrepared = copy.copy(ps)
    noisePrepared[fundIndizes] = 0
    noisePrepared[fullHarmonicBins] = 0
    noiseMean = np.median(noisePrepared[noisePrepared != 0])
    noisePrepared[fundIndizes] = noiseMean
    noisePrepared[fullHarmonicBins] = noiseMean

    noisePower = bandpower(noisePrepared)

    r = 10 * np.log10(pFund / noisePower)

    return r, 10 * np.log10(noisePower)
Extract Signal-to-Noise Ratio for a given audio.
evaluation/features/signal_to_noise_ratio.py