python 对比两个音频文件获取音准音高

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值