需要自定安装相关插件,具体实现代码如下,文件地址通过命令输入即可,执行命令如下

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}")

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐