还差几 中午好🌞🌞🌞
本答案参考通义千问
要使用 Gradio 库实现在 Web UI 中剪切和分类音频的功能,首先需要结合其他 Python 音频处理库,如 pydub
和 gradio
自身提供的功能。以下是一个简化的步骤和示例代码,实现了你所描述的需求:
安装所需的库
pip install gradio pydub
准备音频数据
假设你已经有一段包含多个人语音的wav或mp3文件,并将其存储在一个名为 audio_file.mp3
的文件中。
定义音频处理函数(包括切割和分类)
import os
from pydub import AudioSegment
from pydub.playback import play
def cut_audio_and_classify(file_path, start_time, end_time, speaker_label):
# 加载原始音频
audio = AudioSegment.from_mp3(file_path)
# 切割音频片段
clip = audio[start_time*1000:end_time*1000] # 注意:时间单位为毫秒
# 保存切割后的音频片段(这里假设有一个 speakers 文件夹用于分类)
output_folder = "speakers/" + speaker_label
if not os.path.exists(output_folder):
os.makedirs(output_folder)
output_file_path = f"{output_folder}/{os.path.basename(file_path).split('.')[0]}_{speaker_label}_{int(start_time)}_{int(end_time)}.mp3"
clip.export(output_file_path, format="mp3")
# 播放音频片段以确认
play(clip)
return {"status": "success", "output_file": output_file_path}
# 示例切割时间范围和分类
start_time_1 = 5 # 秒
end_time_1 = 10 # 秒
speaker_label_1 = "PersonA"
start_time_2 = 15 # 秒
end_time_2 = 20 # 秒
speaker_label_2 = "PersonB"
# 调整切割时间和分类后调用函数
cut_audio_and_classify("audio_file.mp3", start_time_1, end_time_1, speaker_label_1)
cut_audio_and_classify("audio_file.mp3", start_time_2, end_time_2, speaker_label_2)
创建 Gradio UI 实例
import gradio as gr
# 创建一个 Gradio 函数输入参数,包括音频文件、切割起始时间、结束时间和分类标签
def process_audio(file):
# 使用上述的 cut_audio_and_classify 函数处理音频
output = cut_audio_and_classify(file.file.name, file["start"], file["end"], file["speaker"])
return output
# 创建一个包含三个输入字段的 Gradio UI,分别对应音频文件、切割开始时间和结束时间,以及分类标签
inputs = [
gr.inputs.File(type="audio", label="选择音频文件"),
gr.inputs.Slider(min=0, max=len(audio), value=start_time_1, step=1, label="切割开始时间 (秒)"),
gr.inputs.Slider(min=0, max=len(audio), value=end_time_1, step=1, label="切割结束时间 (秒)"),
gr.inputs.Radio(["PersonA", "PersonB"], default=speaker_label_1, label="分类")
]
outputs = [gr.outputs.Text(label="输出文件路径")]
# 创建 Gradio 定义
title = "音频剪切与分类 Web UI"
description = "通过 UI 输入音频文件、切割时间和分类,对音频进行分割并保存到对应的文件夹中。"
article = "<p style='color:grey;'>提示:按回车键预览切割后的音频。</p>"
gr.Interface(process_audio, inputs, outputs, title=title, description=description, article=article,
examples=[{"input": {"file": open("audio_file.mp3", "rb"), "start": start_time_1, "end": end_time_1, "speaker": speaker_label_1},
"output": {"status": "success", "output_file": "path_to_output_file.mp3"}}]).launch()
最后,运行上面的代码会启动一个基于 Gradio 的 Web UI,用户可以通过上传音频文件、设置切割时间和分类,从而实现音频的自动切割并保存至指定分类文件夹中。注意,这里的 examples
参数用于向 Gradio 展示初始使用案例,可以根据实际音频文件和切割时间配置这些例子。