Error in user YAML: (<unknown>): found a tab character that violate indentation while scanning a plain scalar at line 3 column 3
---
- oeasy Python 0825
- 这是 oeasy 系统化 Python 教程,从基础一步步讲,扎实、完整、不跳步。愿意花时间学,就能真正学会。
- 本教程同步发布在:
- 个人网站: `https://oeasy.org`
- 蓝桥云课: `https://www.lanqiao.cn/courses/3584`
- GitHub: `https://github.com/overmind1980/oeasy-python-tutorial`
- Gitee: `https://gitee.com/overmind1980/oeasypython`
---wget https://labfile.shiyanlou.com/courses/3584/%E7%8E%8B%E8%80%85%E8%8D%A3%E8%80%80_%E6%89%81%E9%B9%8A_%E7%94%9F%E5%AD%98%E8%BF%98%E6%98%AF%E6%AD%BB%E4%BA%A1.mp3
pip install librosa
import librosa
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['WenQuanYi Zen Hei'] # 设置文泉驿黑字体
plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题
# 加载音频文件
y, sr = librosa.load('王者荣耀_扁鹊_生存还是死亡.mp3')
# 绘制波形图
plt.figure(figsize=(12, 4))
plt.plot(y)
plt.title('音频波形图')
plt.xlabel('采样点')
plt.ylabel('振幅')
plt.show()
import librosa
import librosa.display
import numpy as np
import matplotlib.pyplot as plt
# 加载音频文件
y, sr = librosa.load('audio.mp3')
# 计算短时傅里叶变换 (STFT)
D = librosa.stft(y)
# 将幅度转换为分贝单位
D_db = librosa.amplitude_to_db(np.abs(D), ref=np.max)
# 创建频谱图
plt.figure(figsize=(12, 4))
librosa.display.specshow(D_db, sr=sr, x_axis='time', y_axis='hz')
plt.colorbar(format='%+2.0f dB')
plt.title('频谱图')
plt.show()
import librosa
import librosa.display
import numpy as np
import matplotlib.pyplot as plt
y, sr = librosa.load('audio.mp3')
mel_spect = librosa.feature.melspectrogram(y=y, sr=sr)
mel_spect_db = librosa.power_to_db(mel_spect, ref=np.max)
plt.figure(figsize=(12, 4))
librosa.display.specshow(mel_spect_db, sr=sr, x_axis='time', y_axis='mel')
plt.colorbar(format='%+2.0f dB')
plt.title('梅尔频谱图')
plt.show()
主要区别:
-
频谱图(Spectrogram) :
- 使用线性频率刻度
- 直接显示声音的频率分量
- 使用 librosa.stft() 进行短时傅里叶变换
- y轴使用 y_axis='hz'
-
梅尔频谱图(Mel Spectrogram) :
- 使用梅尔刻度(模拟人耳感知)
- 在低频部分分辨率更高
- 使用 librosa.feature.melspectrogram()
- y轴使用 y_axis='mel' 梅尔频谱图更适合音乐分析,因为它更接近人耳的感知方式。而普通频谱图则更适合需要精确频率分析的场景。
你可以尝试运行这两种不同的频谱图,观察它们的区别。特别注意观察y轴的刻度,你会发现梅尔频谱图在低频部分的分辨率明显更高。
import librosa
import librosa.display
import matplotlib.pyplot as plt
import numpy as np
y, sr = librosa.load('audio.mp3')
chroma = librosa.feature.chroma_stft(y=y, sr=sr)
plt.figure(figsize=(12, 4))
librosa.display.specshow(chroma, y_axis='chroma')
plt.colorbar()
plt.title('色度图')
plt.show()
import librosa
import matplotlib.pyplot as plt
y, sr = librosa.load('audio.mp3')
mfcc = librosa.feature.mfcc(y=y, sr=sr)
plt.figure(figsize=(12, 4))
librosa.display.specshow(mfcc, x_axis='time')
plt.colorbar()
plt.title('MFCC')
plt.show()
import librosa
import matplotlib.pyplot as plt
y, sr = librosa.load('audio.mp3')
onset_env = librosa.onset.onset_strength(y=y, sr=sr)
plt.figure(figsize=(12, 4))
plt.plot(onset_env)
plt.title('节奏强度')
plt.show()
- 本文来自 oeasy Python 系统教程。
- 想完整、扎实学 Python,
- 搜索 oeasy 即可。



