需要自定安装相关插件,具体实现代码如下,文件地址通过命令输入即可,执行命令如下
python3 music.py pathAudio1 pathAudio2
music.py文件代码如下
import librosa
import numpy as np
import json
import sys
import logging
# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
def load_audio(file_path):
try:
y, sr = librosa.load(file_path)
return y, sr
except Exception as e:
logging.error(f"Failed to load audio file {file_path}: {e}")
raise
def extract_pitches(y, sr):
pitches, magnitudes = librosa.piptrack(y=y, sr=sr)
pitch = [pitches[index, t] for t in range(pitches.shape[1]) for index in [magnitudes[:, t].argmax()]]
avg_pitch = np.mean([p for p in pitch if p > 0])
return avg_pitch
def extract_tempo(y, sr):
tempo, _ = librosa.beat.beat_track(y=y, sr=sr)
return tempo
def analyze_audio(file_path):
y, sr = load_audio(file_path)
avg_pitch = extract_pitches(y, sr)
tempo = extract_tempo(y, sr)
return avg_pitch, tempo
def compare_audios(file1, file2):
pitch1, tempo1 = analyze_audio(file1)
pitch2, tempo2 = analyze_audio(file2)
# 计算差异
pitch_diff = str(pitch2 - pitch1)
tempo_diff = str(tempo2 - tempo1)
# 构建结果字典
result = {
"first_audio": {
"pitch": str(pitch1),
"tempo": str(tempo1)
},
"second_audio": {
"pitch": str(pitch2),
"tempo": str(tempo2)
},
"different": {
"pitch": str(pitch_diff),
"tempo": str(tempo_diff)
}
}
# 转换为 JSON
return json.dumps(result, indent=4)
# 示例文件路径
if len(sys.argv) != 3:
logging.error("Usage: python script.py <file1> <file2>")
sys.exit(1)
file1 = sys.argv[1]
file2 = sys.argv[2]
# 运行对比并输出结果
try:
result_json = compare_audios(file1, file2)
print(result_json)
except Exception as e:
logging.error(f"An error occurred: {e}")