『语音信号处理』语音库 librosa 学习

本文介绍了音频处理库librosa的基本操作,包括音频读取、重采样、计算时长、写入音频、过零率计算、波形图绘制、短时傅里叶变换及逆变换、幅度和功率转dB、频谱图展示、梅尔滤波器组应用以及梅尔频谱和MFCC特征提取。这些功能对于音频分析和处理至关重要。
摘要由CSDN通过智能技术生成


前言

安装 librosa

sudo apt-get install libsndfile1
pip install librosa

音频读取

示例:

data, sr = librosa.load(path, sr=22050, mono=Ture, offset=0.0, duration=None)

参数值:

  • mono :bool,是否将信号转换为单声道
  • offset :float,在此时间之后开始阅读(以秒为单位)
  • duration:float,持续时间,仅加载这么多的音频(以秒为单位)

返回值:

  • data : 振幅矩阵,len(data) 为其采样个数;
  • sr : 采样率,记录声音文件时的采样频率,如果需要读取原始采样率,需要设定参数 sr=None

重采样

orig_sr = librosa.get_samplerate(path) 	# 读取采样率
y_hat = librosa.resample(y, orig_sr, target_sr, fix=True, scale=False) 

重新采样从 orig_sr 到 target_sr 的时间序列

参数:

  • y :音频时间序列。可以是单声道或立体声。
  • orig_sr :y的原始采样率
  • target_sr :目标采样率
  • fix:bool,调整重采样信号的长度,使其大小恰好为 l e n ( y ) o r i g _ s r ∗ t a r g e t _ s r = t ∗ t a r g e t _ s r \frac{len(y)}{orig\_sr}*target\_sr =t*target\_sr orig_srlen(y)target_sr=ttarget_sr
  • scale:bool,缩放重新采样的信号,以使 y 和 y_hat 具有大约相等的总能量。

返回值:

  • y_hat :重采样之后的音频数组

读取时长

t = librosa.get_duration(y=None, sr=22050, S=None, n_fft=2048, hop_length=512, center=True, filename=None)

计算时间序列的的 持续时间(以秒为单位)

参数:

  • y :音频时间序列
  • sr :音频采样率
  • S :STFT矩阵或任何STFT衍生的矩阵(例如,色谱图或梅尔频谱图)。根据频谱图输入计算的持续时间仅在达到帧分辨率之前才是准确的。如果需要高精度,则最好直接使用音频时间序列。
  • n_fft :S 的 FFT 窗口大小
  • hop_length :S列之间的音频样本数
  • center :bool
    • 如果为True,则 S [:, t] 的中心为 y [t * hop_length]
    • 如果为False,则 S [:, t] 从 y[t * hop_length] 开始
  • filename :如果提供,则所有其他参数都将被忽略,并且持续时间是直接从音频文件中计算得出的。

返回:

  • t :持续时间(以秒为单位)

写音频

librosa.output.write_wav(path, y, sr, norm=False)

将时间序列输出为 .wav 文件

参数:

  • path:保存输出 wav 文件的路径
  • y :音频时间序列。
  • sr :y 的采样率
  • norm:bool,是否启用幅度归一化。将数据缩放到 [-1,+1] 范围。

过零率

y, sr = librosa.load(librosa.util.example_audio_file())
print(librosa.feature.zero_crossing_rate(y))
# array([[ 0.134,  0.139, ...,  0.387,  0.322]])

计算音频时间序列的过零率。

参数:

  • y :音频时间序列
  • frame_length :帧长
  • hop_length :帧移
  • center:bool,如果为True,则通过填充 y 的边缘来使帧居中。

返回:

  • zcr:zcr[0,i] 是第 i 帧中的过零率

波形图

librosa.display.waveplot(y, sr=22050, x_axis='time', offset=0.0, ax=None)

绘制波形的幅度包络线

参数:

  • y :音频时间序列
  • sr :y 的采样率
  • x_axis :str {‘time’,‘off’,‘none’} 或 None,如果为“时间”,则在 x 轴上给定时间刻度线。
  • offset:水平偏移(以秒为单位)开始波形图
# 示例
import librosa.display
import matplotlib.pyplot as plt

y, sr = librosa.load(librosa.util.example_audio_file(), duration=10)
librosa.display.waveplot(y, sr=sr)
plt.show()

短时傅里叶变换

librosa.stft(y, n_fft=2048, hop_length=None, win_length=None, window='hann', center=True, pad_mode='reflect')

短时傅立叶变换(STFT),返回一个复数矩阵使得 D(f, t)

  • 复数的实部:np.abs(D(f, t)) 频率的振幅
  • 复数的虚部:np.angle(D(f, t)) 频率的相位

参数:

  • y:音频时间序列
  • n_fft:FFT窗口大小,n_fft = hop_length + overlapping
  • hop_length:帧移,如果未指定,则默认 win_length / 4。
  • win_length:每一帧音频都由 window() 加窗。窗长 win_length,然后用零填充以匹配 N_FFT。
    默认 win_length=n_fft。
  • window:字符串,元组,数字,函数 shape =(n_fft, )
    • 窗口(字符串,元组或数字);
    • 窗函数,例如 scipy.signal.hanning
    • 长度为 n_fft 的向量或数组
  • center:bool
    • 如果为True,则填充信号y,以使帧 D [:, t] 以 y [t * hop_length] 为中心。
    • 如果为False,则 D [:, t] 从 y [t * hop_length] 开始
  • dtype:D的复数值类型。默认值为 64-bit complex 复数
  • pad_mode:如果 center = True,则在信号的边缘使用填充模式。默认情况下,STFT使用 reflection padding。

返回:

  • STFT矩阵,shape =(1 + n f f t 2 \frac{n_{fft} }{2} 2nfft,t)

短时傅里叶逆变换

librosa.istft(stft_matrix, hop_length=None, win_length=None, window='hann', center=True, length=None)

短时傅立叶逆变换(ISTFT),将复数值 D(f, t) 频谱矩阵转换为时间序列y,窗函数、帧移等参数应与stft相同

参数:

  • stft_matrix :经过STFT之后的矩阵
  • hop_length :帧移,默认为 w i n l e n g t h 4 \frac{win_{length}}{4} 4winlength
  • win_length :窗长,默认为 n_fft
  • window:字符串,元组,数字,函数或 shape = (n_fft, )
    • 窗口(字符串,元组或数字)
    • 窗函数,例如scipy.signal.hanning
    • 长度为 n_fft 的向量或数组
  • center:bool
    • 如果为 True,则假定D具有居中的帧
    • 如果为 False,则假定D具有左对齐的帧
  • length:如果提供,则输出y为零填充或剪裁为精确长度音频

返回:

  • y :时域信号

幅度转dB

librosa.amplitude_to_db(S, ref=1.0)

将幅度频谱转换为dB标度频谱。也就是对 S 取对数。
与这个函数相反的是 librosa.db_to_amplitude(S)

参数:

  • S :输入幅度
  • ref :参考值,振幅 abs(S)相对于 ref 进行缩放, 20 ∗ l o g 10 ( S r e f ) 20*log_{10}(\frac{S}{ref}) 20log10(refS)

返回:

  • dB为单位的S

功率转dB

librosa.core.power_to_db(S, ref=1.0)

将功率谱(幅度平方)转换为分贝(dB)单位。
与这个函数相反的是 librosa.db_to_power(S)

参数:

  • S :输入幅度
  • ref :参考值,振幅 abs(S)相对于 ref 进行缩放, 10 ∗ l o g 10 ( S r e f ) 10*log_{10}(\frac{S}{ref}) 10log10(refS)

返回:

  • dB为单位的S

频谱图

librosa.display.specshow(data, x_axis=None, y_axis=None, sr=22050, hop_length=512)

参数:

  • data:要显示的矩阵
  • sr :采样率
  • hop_length :帧移
  • x_axis 、y_axis :x和y轴的范围
  • 频率类型
    • ‘linear’,‘fft’,‘hz’:频率范围由 FFT 窗口和采样率确定
    • ‘log’:频谱以对数刻度显示
    • ‘mel’:频率由mel标度决定
  • 时间类型
    • time:标记以毫秒,秒,分钟或小时显示。值以秒为单位绘制。
    • s:标记显示为秒。
    • ms:标记以毫秒为单位显示。
  • 所有频率类型均以Hz为单位绘制

示例:

import librosa.display
import numpy as np
import matplotlib.pyplot as plt

y, sr = librosa.load(librosa.util.example_audio_file())
plt.figure()

D = librosa.amplitude_to_db(np.abs(librosa.stft(y)), ref=np.max)	# 将振幅谱图转换为 db_scale 谱图
plt.subplot(2, 1, 1)
librosa.display.specshow(D, y_axis='linear')
plt.colorbar(format='%+2.0f dB')
plt.title('线性频率功率谱')

plt.subplot(2, 1, 2)
librosa.display.specshow(D, y_axis='log')
plt.colorbar(format='%+2.0f dB')
plt.title('对数频率功率谱')
plt.show()

Mel滤波器组

librosa.filters.mel(sr, n_fft, n_mels=128, fmin=0.0, fmax=None, htk=False, norm=1)

创建一个滤波器组矩阵以将 FFT 合并成 Mel 频率

参数:

  • sr :输入信号的采样率
  • n_fft :FFT组件数
  • n_mels :产生的梅尔带数
  • fmin :最低频率(Hz)
  • fmax:最高频率(以Hz为单位)。如果为 None,则使用 fmax = sr / 2.0
  • norm:{None,1,np.inf} [标量]
    • 如果为1,则将三角 mel 权重除以mel带的宽度(区域归一化)。
    • 否则,保留所有三角形的峰值为1.0

返回: Mel变换矩阵

melfb = librosa.filters.mel(22050, 2048)
# array([[ 0.   ,  0.016, ...,  0.   ,  0.   ],
#        [ 0.   ,  0.   , ...,  0.   ,  0.   ],
#        ...,
#        [ 0.   ,  0.   , ...,  0.   ,  0.   ],
#        [ 0.   ,  0.   , ...,  0.   ,  0.   ]])
import matplotlib.pyplot as plt
plt.figure()
librosa.display.specshow(melfb, x_axis='linear')
plt.ylabel('Mel filter')
plt.title('Mel filter bank')
plt.colorbar()
plt.tight_layout()
plt.show()

梅尔频谱

librosa.feature.melspectrogram(audio, sr=40000, n_fft=1480, hop_length=150, n_mels=256)

提供了时间序列 audio,sr,首先计算其幅值频谱S,然后通过 mel_f.dot(S ** power)将其映射到 mel scale上 。
默认情况下,power=2 在功率谱上运行。

参数:

  • n_mels : 梅尔滤波器的数目
  • sr : 采样率
  • n_fft : 窗口大小
  • power : 幅度谱的指数。例如1代表能量,2代表功率,等等
  • hop_length : 帧移
  • win_length : 窗口的长度为 win_length,默认win_length = n_fft
  • fmax :最高频率

示例:

import librosa.display
import numpy as np
import matplotlib.pyplot as plt

y, sr = librosa.load(librosa.util.example_audio_file())

# 方法一:使用时间序列求Mel频谱
print(librosa.feature.melspectrogram(y=y, sr=sr))
# array([[  2.891e-07,   2.548e-03, ...,   8.116e-09,   5.633e-09],
#        [  1.986e-07,   1.162e-02, ...,   9.332e-08,   6.716e-09],
#        ...,
#        [  3.668e-09,   2.029e-08, ...,   3.208e-09,   2.864e-09],
#        [  2.561e-10,   2.096e-09, ...,   7.543e-10,   6.101e-10]])

# 方法二:使用stft频谱求Mel频谱
D = np.abs(librosa.stft(y)) ** 2  			# stft频谱
S = librosa.feature.melspectrogram(S=D)  	# 使用stft频谱求Mel频谱

plt.figure(figsize=(10, 4))
librosa.display.specshow(librosa.power_to_db(S, ref=np.max), 
						 y_axis='mel', fmax=8000, x_axis='time')
plt.colorbar(format='%+2.0f dB')
plt.title('Mel spectrogram')
plt.tight_layout()
plt.show()

提取MFCC系数

MFCC 特征是一种在自动语音识别和说话人识别中广泛使用的特征。关于MFCC特征的详细信息,有兴趣的可以参考博客http:// blog.csdn.net/zzc15806/article/details/79246716。在librosa中,提取MFCC特征只需要一个函数:

librosa.feature.mfcc(y=None, sr=22050, S=None, n_mfcc=20, dct_type=2, norm='ortho', **kwargs)

参数:

  • y:音频数据
  • sr:采样率
  • S:np.ndarray,对数功能梅尔谱图
  • n_mfcc:int>0,要返回的MFCC数量
  • dct_type:None, or {1, 2, 3} 离散余弦变换(DCT)类型。默认情况下,使用DCT类型2。
  • norm: None or ‘ortho’ 规范。
    • 如果 dct_type 为 2 或 3,则设置 norm =‘ortho’ 使用正交 DCT 基础。
    • 标准化不支持 dct_type = 1。

返回:

  • M: MFCC序列
import librosa

y, sr = librosa.load('./train_nb.wav', sr=16000)
# 提取 MFCC feature
mfccs = librosa.feature.mfcc(y=y, sr=sr, n_mfcc=40)

print(mfccs.shape)        # (40, 65)
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

libo-coder

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值