- ubuntu系统、python2.7,安装librosa,需要joblib==0.11.0版本,版本不匹配可能会报librosa:TypeError: expected string or buffer
librosa
#-*-coding:utf-8-*-
import librosa
import numpy as np
def get_spectrograms(fpath):
'''Returns normalized log(melspectrogram) and log(magnitude) from `sound_file`.
Args:
sound_file: A string. The full path of a sound file.
Returns:
mel: A 2d array of shape (T, n_mels) <- Transposed
mag: A 2d array of shape (T, 1+n_fft/2) <- Transposed
'''
# num = np.random.randn()
# if num < .2:
# y, sr = librosa.load(fpath, sr=hp.sr)
# else:
# if num < .4:
# tempo = 1.1
# elif num < .6:
# tempo = 1.2
# elif num < .8:
# tempo = 0.9
# else:
# tempo = 0.8
# cmd = "ffmpeg -i {} -y ar {} -hide_banner -loglevel panic -ac 1 -filter:a atempo={} -vn temp.wav".format(fpath, hp.sr, tempo)
# os.system(cmd)
# y, sr = librosa.load('temp.wav', sr=hp.sr)
# Loading sound file
y, sr = librosa.load(fpath, sr=22050)
# Trimming
y, _ = librosa.effects.trim(y)
# Preemphasis
y = np.append(y[0], y[1:] - 0.95 * y[:-1])
# stft
linear = librosa.stft(y=y,n_fft=2048,hop_length=int(0.0125*22050),win_length=int(0.05*22050))#(1025,54)
# magnitude spectrogram
mag = np.abs(linear) # (1+n_fft//2, T) #(1025,54)
# mel spectrogram
mel_basis = librosa.filters.mel(22050, 2048, 80) # (n_mels, 1+n_fft//2) #(80,1025)
mel = np.dot(mel_basis, mag) # (n_mels, t) #(80, 54)
# to decibel
mel = 20 * np.log10(np.maximum(1e-5, mel))
mag = 20 * np.log10(np.maximum(1e-5, mag))
# normalize
mel = np.clip((mel - 20 + 100) / 100, 1e-8, 1)#(80, 54)
mag = np.clip((mag - 20 + 100) / 100, 1e-8, 1)#(1025, 54)
# Transpose
mel = mel.T.astype(np.float32) # (T, n_mels) #(54, 80)
mag = mag.T.astype(np.float32) # (T, 1+n_fft//2) #(54, 1025)
return mel, mag
if __name__ == "__main__":
get_spectrograms("1-1.wav")
T表示时间方向,帧率为22050