librosa

  • 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值