import librosa | |
import numpy as np | |
import matplotlib.pyplot as plt | |
import librosa.display | |
def extract_melody(audio_file): | |
# 加载音频文件 | |
y, sr = librosa.load(audio_file) | |
# 提取旋律(和声成分) | |
y_harmonic = librosa.effects.harmonic(y) # 注意这里的变化 | |
# 计算音高特征(Chroma) | |
chroma = librosa.feature.chroma_cqt(y=y_harmonic, sr=sr) | |
# 显示音高特征 | |
plt.figure(figsize=(10, 4)) | |
librosa.display.specshow(chroma, y_axis='chroma', x_axis='time') | |
plt.colorbar() | |
plt.title('Chromagram') | |
plt.tight_layout() | |
plt.show() | |
# 替换为你的音频文件路径 | |
audio_file = 'your_song.mp3' | |
extract_melody(audio_file) | |