用AI做了个MP3节拍生成json

参考 Creator3D:炫动球球(音乐游戏)实现分享
对python零基础, 摸索了几个小时靠, 代码靠AI纠正过来了, 主要老哥的代码已经跑不了又不好挖坟去问, 先去官网装个最新稳定版python, 这个网上教程多就不说了, 主要是安装的时候path要有, 然后cmd里面装librosa, 所有东西都会自动装上, 然后把AI重写的代码放上去就对了

官方啥时候把音频加速端上来啊, 第三方库用得挺痛苦的, 就是个简单的2倍速需求

2赞

import os

import json

import librosa

import numpy as np

from pathlib import Path

def analyze_audio_files(directory_path, output_file=“level.json”):

"""

分析指定目录下的所有MP3文件,提取名称、时长和节奏信息



参数:

directory_path (str): 包含MP3文件的目录路径

output_file (str): 输出JSON文件名

"""

# 支持的文件扩展名

audio_extensions = {'.mp3', '.wav', '.flac', '.ogg'}



# 获取目录中的所有音频文件

audio_files = []

for file in Path(directory_path).iterdir():

    if file.suffix.lower() in audio_extensions and file.is_file():

        audio_files.append(file)



if not audio_files:

    print(f"在目录 {directory_path} 中未找到音频文件")

    return



results = []



for file_path in audio_files:

    try:

        print(f"正在分析: {file_path.name}")

       

        # 加载音频文件

        y, sr = librosa.load(str(file_path))

       

        # 计算音频时长(秒)

        duration = librosa.get_duration(y=y, sr=sr)

       

        # 计算节奏信息

        # 1. 计算onset强度

        onset_env = librosa.onset.onset_strength(y=y, sr=sr)

       

        # 2. 检测峰值(节拍)

        peaks = librosa.util.peak_pick(onset_env, pre_max=3, post_max=3, pre_avg=3, post_avg=5, delta=0.5, wait=10)

       

        # 3. 将帧转换为时间

        peak_times = librosa.frames_to_time(peaks, sr=sr)

        # 计算节拍间隔

        intervals = np.diff(peak_times) if len(peak_times) > 1 else np.array([])

        # 格式化时间数据,保留4位小数

        formatted_peak_times = [round(float(t), 4) for t in peak_times]

        formatted_intervals = [round(float(i), 4) for i in intervals]

        # 添加到结果列表

        results.append({

            "name": file_path.name,

            "duration": round(float(duration), 4),

            "rhythm": {

                "beats": formatted_peak_times,

                "intervals": formatted_intervals

            }

        })

    except Exception as e:

        print(f"分析文件 {file_path.name} 时出错: {str(e)}")



# 将结果写入JSON文件

with open(output_file, 'w', encoding='utf-8') as f:

    json.dump(results, f, indent=4, ensure_ascii=False)



print(f"分析完成! 结果已保存到 {output_file}")

if name == “main”:

# 设置包含MP3文件的目录路径

music_directory = "music"  # 修改为你的音乐目录路径



# 确保目录存在

if not os.path.exists(music_directory):

    print(f"目录 '{music_directory}' 不存在")

else:

    analyze_audio_files(music_directory)

现在有 AI 就是好啊,以前没有 AI,要做这个节拍是不容易

赞赞赞 :+1::+1::+1:

大佬你好 :smiling_face_with_three_hearts: 没看到你的贴子我都不知道这东西这么好用

干货!!!
点赞.