Librosa基础使用
创始人
2025-06-01 06:05:29

Librosa基础使用

参考:《语音识别技术》、《入门语音识别》

主要内容:

  • 载入音频 获取数字表示
  • 获取时长 采样率
  • 去除两端沉默
  • 播放音频
  • 波形图
  • Spectogram 频谱图
  • 梅尔频率倒谱系数(MFCC)
  • 过零率
  • 频谱质心: Spectral Centroid
  • 频谱带宽:Spectral Bandwidth
  • 频谱滚降
  • 色度特征:Chroma Feature
  • 间距和幅度
  • chroma特征 与 CQT (Constant-Q)特征
  • 完整的生成及绘制cq谱示例

简单示例:

load:    - `y,sr = librosa.load(wav_file,sr=22050);`mfcc:- `librosa.feature.mfcc(y=y,n_mfcc=64,sr=sr,n_mels=64)`mel:- `librosa.feature.melspectrogram(y=y,sr=sr,n_mels=64)`

载入音频 获取数字表示

x , sr = librosa.load("./乌梅子酱-李荣浩.wav", sr=22050)
print(x.shape, sr)
(5672672,) 22050

获取时长 采样率


d = librosa.get_duration(y=x, sr=22050, S=None, n_fft=2048, hop_length=512, center=True, filename=None)
sr = librosa.get_samplerate("./乌梅子酱-李荣浩.wav")
sr,d
(44100, 257.26403628117913)

去除两端沉默

audio_file, _ = librosa.effects.trim(x)
print('Audio File:', audio_file, '\n')
print('Audio File shape:', np.shape(audio_file))
Audio File: [-3.2841001e-04 -3.0707751e-04 -2.6176337e-04 ...  2.7146576e-052.7009228e-04  2.0527366e-05] Audio File shape: (5627904,)

播放音频


# import IPython# IPython.display.Audio("./乌梅子酱-李荣浩.wav")

波形图

plt.figure(figsize=(20, 5))
librosa.display.waveplot(x, sr=sr)
plt.show()

在这里插入图片描述

Spectogram 频谱图:

  • 频谱图(Spectogram)是声音频率随时间变化的频谱的可视化表示,是给定音频信号的频率随时间变化的表示。
  • ‘.stft’ 将数据转换为短期傅里叶变换。 STFT转换信号,以便我们可以知道给定时间给定频率的幅度。 使用 STFT,我们可以确定音频信号在给定时间播放的各种频率的幅度。
  • Spectrogram特征是目前在语音识别和环境声音识别中很常用的一个特征,由于CNN在处理图像上展现了强大的能力,使得音频信号的频谱图特征的使用愈加广泛,甚至比MFCC使用的更多。
X = librosa.stft(x)
Xdb = librosa.amplitude_to_db(abs(X))
plt.figure(figsize=(20, 5))
librosa.display.specshow(Xdb, sr=sr, x_axis='time', y_axis='hz')
plt.colorbar()
plt.show()

在这里插入图片描述

梅尔频率倒谱系数(MFCC)

  • 信号的梅尔频率倒谱系数 (MFCC) 是一小组特征(通常约为 10-20),它们简明地描述了频谱包络的整体形状。在 MIR 中,它经常被用来描述音色。
mfccs = librosa.feature.mfcc(y=x, sr=sr)
mfccs.shapeplt.figure(figsize=(20, 5))
librosa.display.specshow(mfccs, sr=sr, x_axis='time')
plt.colorbar()
plt.show()

在这里插入图片描述

过零率

  • 过零率(zero-crossing rate,ZCR)是指一个信号的符号变化的比率,例如信号从正数变成负数,或反过来。这个特征已在语音识别和音乐信息检索领域得到广泛使用,是分类敲击声的关键特征。为真时为1,否则为0。在一些应用场景下,只统计“正向”或“负向”的变化,而不是所有的方向。
n0 = 7000
n1 = 7025
plt.figure(figsize=(14, 5))
plt.plot(x[n0:n1])
plt.show()

在这里插入图片描述

zero_crossings = librosa.zero_crossings(x[n0:n1], pad=False)
zero_crossings.shape, zero_crossings.sum()
((25,), 1)
# 可以使用整个音频来遍历这个并推断出整个数据的过零
zcrs = librosa.feature.zero_crossing_rate(x)
print(zcrs.shape)plt.figure(figsize=(14, 5))
plt.plot(zcrs[0])

在这里插入图片描述

频谱质心: Spectral Centroid

  • 频谱质心(维基百科)表示频谱能量集中在哪个频率上
spectral_centroids = librosa.feature.spectral_centroid(x, sr=sr)[0]
spectral_centroids.shapeframes = range(len(spectral_centroids))
t = librosa.frames_to_time(frames)import sklearn
def normalize(x, axis=0):return sklearn.preprocessing.minmax_scale(x, axis=axis)plt.figure(figsize=(20, 5))
librosa.display.waveplot(x, sr=sr, alpha=0.4)
plt.plot(t, normalize(spectral_centroids), color='r')

在这里插入图片描述

频谱带宽:Spectral Bandwidth

  • ibrosa.feature.spectral_bandwidth 可以用来计算p-order频谱带宽:
spectral_bandwidth_2 = librosa.feature.spectral_bandwidth(x+0.01, sr=sr)[0]
spectral_bandwidth_3 = librosa.feature.spectral_bandwidth(x+0.01, sr=sr, p=3)[0]
spectral_bandwidth_4 = librosa.feature.spectral_bandwidth(x+0.01, sr=sr, p=4)[0]
plt.figure(figsize=(20, 5))
librosa.display.waveplot(x, sr=sr, alpha=0.4)
plt.plot(t, normalize(spectral_bandwidth_2), color='r')
plt.plot(t, normalize(spectral_bandwidth_3), color='g')
plt.plot(t, normalize(spectral_bandwidth_4), color='y')
plt.legend(('p = 2', 'p = 3', 'p = 4'))

在这里插入图片描述

频谱滚降

  • 频谱衰减是总频谱能量的特定百分比所在的频率。
spectral_rolloff = librosa.feature.spectral_rolloff(x+0.01, sr=sr)[0]
plt.figure(figsize=(20, 5))
librosa.display.waveplot(x, sr=sr, alpha=0.4)
plt.plot(t, normalize(spectral_rolloff), color='r')

在这里插入图片描述

色度特征:Chroma Feature

  • 色度向量 (Wikipedia) 是一个典型的 12 元素特征向量,指示每个音高类别{C, C#, D, D#, E, …, B}的能量是多少存在于信号中。
chromagram = librosa.feature.chroma_stft(x, sr=sr, hop_length=512)
plt.figure(figsize=(20, 5))
librosa.display.specshow(chromagram, x_axis='time', y_axis='chroma', hop_length=512, cmap='coolwarm')

在这里插入图片描述

间距和幅度

  • 音高是声音的感知属性,在与频率相关的尺度上排序,或者更常见的是,音高是可以判断声音在与音乐旋律相关的意义上“更高”和“更低”的质量。
pitches, magnitudes = librosa.piptrack(y=x, sr=sr)
print(pitches)
[[0. 0. 0. ... 0. 0. 0.][0. 0. 0. ... 0. 0. 0.][0. 0. 0. ... 0. 0. 0.]...[0. 0. 0. ... 0. 0. 0.][0. 0. 0. ... 0. 0. 0.][0. 0. 0. ... 0. 0. 0.]]

chroma特征 与 CQT (Constant-Q)特征

chroma特征:

  • Chroma 特征是一种与时序相关的特征,广泛应用在音乐版本鉴别任务中,并产生 了许多不同的变种方案,Chroma 特征将整个频域折叠在音乐中的 十二半音上,反映了各个时间点下的十二半音的能量分布。该种特征能够忽略音乐的 音色信息,保留音乐的旋律特性。

CQT (Constant-Q)特征:

  • Constant-Q 特征谱是音频经过 Constant-Q transform(CQT)得到的。在音乐的 十二平均律中,一个八度音程可以划分为十二个半音,相邻的半音具有相等的音高差。 其中音高差相等在频率上代表相邻半音的频率之差的比为一个常数𝑄。Constant-Q 特征 即在十二半音下计算每一个半音的频谱分量。
  • CQT结果数据由多帧(时间步)构成(帧序按时间顺序),每帧包含7个八度,每个八度有12个值。CQT结果由多个时间步(512帧)构成,每帧包含7个八度、每个八度12个值,即84个值

其他

  • amplitude_to_db:将幅度频谱转换为dB标度频谱。也就是对S取对数。与这个函数相反的是librosa.db_to_amplitude(S)
  • power_to_db:将功率谱(幅度平方)转换为分贝(dB)单位,与这个函数相反的是librosa.db_to_power(S)
## Constant-Q transform# cqt_a = librosa.cqt(x)
cqt_a = np.abs(librosa.cqt(x))# 将幅度频谱转换为dB标度频谱。也就是对S取对数。与这个函数相反的是librosa.db_to_amplitude(S)
# 这也是我们较为常用的绘制前要做的变换
cqt_a = librosa.amplitude_to_db(cqt_a, ref=np.max)# 将功率谱(幅度平方)转换为分贝(dB)单位,与这个函数相反的是librosa.db_to_power(S)
# 与上一个一致
# cqt_a = librosa.power_to_db(cqt_a**2, ref=np.max)plt.figure(figsize=(20, 5))
librosa.display.specshow(cqt_a, sr=sr, x_axis='time', y_axis='hz')
plt.colorbar(format='%+2.0f dB')
plt.show()

在这里插入图片描述


## chroma cqt
chromagram = librosa.feature.chroma_cqt(x, sr=sr, hop_length=512)
plt.figure(figsize=(20, 5))
librosa.display.specshow(chromagram, x_axis='time', y_axis='chroma', hop_length=512, cmap='coolwarm')
plt.colorbar(format='%+.2f dB')
plt.show()

在这里插入图片描述

完整的生成及绘制cq谱示例

import warnings
warnings.filterwarnings("ignore")
import matplotlib.pyplot as plt
import numpy as np
from pydub import AudioSegment
import librosa
from librosa import display
from ffmpy import FFmpeg

def getWAV(in_path, out_path):
#     ff_in_path = './test.mp4'
#     ff_out_path = './test.wav'FFmpeg(inputs={in_path: None}, outputs={out_path: '-ar 22050 -ac 2 -b:a 48k -y'}).run()return out_pathdef getCQT(in_path, out_path, need_abs=False):data, sr = librosa.load(in_path) # 默认加载的sr=22050print(len(data),sr)cqt_v = librosa.cqt(y=data, sr=sr)if need_abs:# 使用np.abs将cqt复数的特征矩阵 转成负数模的形式cqt_v = np.abs(cqt_v) height, length = cqt_v.shapeprint(height, length)np.save(out_path, cqt_v)return cqt_vdef getFileInfo(in_path,fmt="wav"):# 获取音乐相关信息:(音乐时长,帧数,2.5s帧数)sound = AudioSegment.from_file(in_path, format=fmt)# durations_duration_in_milliseconds = len(sound)s_frame_count = sound.frame_count()s_frame_count_2500 = sound.frame_count(ms=2500)print('音乐时长ms:',s_duration_in_milliseconds)print('音频帧数:',s_frame_count)print('2500ms对应音频帧数:',s_frame_count_2500)return s_duration_in_milliseconds,s_frame_count,s_frame_count_2500    getWAV("./乌梅子酱-李荣浩.m4a","./乌梅子酱-李荣浩.wav")
data1 = getCQT("./乌梅子酱-李荣浩.wav","./乌梅子酱-李荣浩.npy",need_abs=True)
getFileInfo("./乌梅子酱-李荣浩.wav")
5672672 22050
84 11080
音乐时长ms: 257264
音频帧数: 5672672.0
2500ms对应音频帧数: 55125.0
def plt_show(cqt_a, sr):cqt_a = librosa.amplitude_to_db(cqt_a, ref=np.max)plt.figure(figsize=(20, 5))librosa.display.specshow(cqt_a, sr=sr, x_axis='time', y_axis='hz')plt.colorbar(format='%+2.0f dB')plt.show()plt_show(data1,22050)

在这里插入图片描述

相关内容

热门资讯

今年我省粮食产量达515.56... (来源:辽宁日报)转自:辽宁日报 图为在中储粮(盘锦)储运有限公司,装运粮食的重型卡车排起长队...
国家发展改革委部署促进投资止跌... (来源:辽宁日报)转自:辽宁日报 新华社北京12月13日电 (记者魏玉坤) 记者13日从全国发展和改...
江苏省实施《中华人民共和国森林... (来源:新华日报) 目 录 第一章 总则 第二章 森林、林木和林地权属管理...
姜堰数字化产品讲“活”理论 (来源:新华日报) □ 本报记者 卢佳乐 通讯员 姜宣 “王教授,您约我‘喝茶论道’,...
联合国维和部队在苏丹遇袭 6人... 转自:财联社【联合国维和部队在苏丹遇袭 6人死亡】财联社12月14日电,当地时间13日,苏丹武装部队...