SenseVoice-small-onnx语音识别实战教程批量音频文件转写与JSON结果解析1. 引言语音识别的新选择在日常工作中我们经常需要处理大量的音频文件转写任务。无论是会议录音整理、访谈内容转录还是多媒体内容处理传统的手工转写方式既耗时又容易出错。SenseVoice-small-onnx语音识别模型的出现为这个问题提供了一个高效的解决方案。这个基于ONNX量化的多语言语音识别服务不仅支持中文、英语、日语、韩语等主流语言还能自动识别粤语等方言。最吸引人的是它能够在10秒音频上实现仅70毫秒的推理速度让批量处理成为可能。本教程将手把手教你如何部署这个语音识别服务并实现批量音频文件的自动转写和结果解析。无论你是开发者还是普通用户都能快速上手使用。2. 环境准备与快速部署2.1 安装必要依赖首先确保你的系统已经安装了Python 3.7或更高版本。然后通过pip安装所需的依赖包pip install funasr-onnx gradio fastapi uvicorn soundfile jieba这些依赖包各自负责不同的功能funasr-onnx核心语音识别库gradio提供Web界面fastapi和uvicorn构建REST API服务soundfile处理音频文件jieba中文分词支持2.2 启动语音识别服务创建一个名为app.py的Python文件内容如下from funasr_onnx import SenseVoiceSmall import os # 确保模型目录存在 model_dir /root/ai-models/danieldong/sensevoice-small-onnx-quant os.makedirs(model_dir, exist_okTrue) # 启动服务实际服务代码会更复杂这里简化说明 print(服务准备就绪请运行完整版app.py)然后通过命令行启动服务python3 app.py --host 0.0.0.0 --port 7860服务启动后你可以通过以下地址访问Web界面http://localhost:7860API文档http://localhost:7860/docs健康检查http://localhost:7860/health3. 批量音频转写实战3.1 准备音频文件在进行批量转写前我们需要先整理好音频文件。建议将所有的音频文件放在同一个目录中并确保它们都是支持的格式如wav、mp3、m4a、flac等。import os import glob def prepare_audio_files(audio_dir, extensions[.wav, .mp3, .m4a, .flac]): 准备待转写的音频文件列表 audio_files [] for ext in extensions: audio_files.extend(glob.glob(os.path.join(audio_dir, f*{ext}))) print(f找到 {len(audio_files)} 个音频文件) return audio_files # 使用示例 audio_directory ./audio_files files_to_transcribe prepare_audio_files(audio_directory)3.2 批量转写实现现在我们来编写批量转写的核心代码import json import time from funasr_onnx import SenseVoiceSmall def batch_transcribe(audio_files, output_dir./results): 批量转写音频文件 # 创建输出目录 os.makedirs(output_dir, exist_okTrue) # 初始化模型 model SenseVoiceSmall( /root/ai-models/danieldong/sensevoice-small-onnx-quant, batch_size10, # 根据你的GPU内存调整 quantizeTrue ) results [] # 分批处理音频文件 for i in range(0, len(audio_files), 10): batch_files audio_files[i:i10] print(f处理批次 {i//10 1}: {len(batch_files)} 个文件) # 执行转写 batch_results model(batch_files, languageauto, use_itnTrue) # 保存结果 for j, result in enumerate(batch_results): audio_file batch_files[j] output_file os.path.join( output_dir, f{os.path.basename(audio_file)}_result.json ) result_data { audio_file: audio_file, transcription: result, timestamp: time.strftime(%Y-%m-%d %H:%M:%S), language: auto_detected } with open(output_file, w, encodingutf-8) as f: json.dump(result_data, f, ensure_asciiFalse, indent2) results.append(result_data) print(f✓ 完成: {os.path.basename(audio_file)}) return results # 使用示例 transcription_results batch_transcribe(files_to_transcribe)3.3 处理进度显示对于大量音频文件的处理显示进度条可以更好地了解处理状态from tqdm import tqdm def batch_transcribe_with_progress(audio_files, output_dir./results): 带进度条的批量转写 os.makedirs(output_dir, exist_okTrue) model SenseVoiceSmall( /root/ai-models/danieldong/sensevoice-small-onnx-quant, batch_size10, quantizeTrue ) results [] # 使用tqdm显示进度条 with tqdm(totallen(audio_files), desc转写进度) as pbar: for i in range(0, len(audio_files), 10): batch_files audio_files[i:i10] batch_results model(batch_files, languageauto, use_itnTrue) for j, result in enumerate(batch_results): audio_file batch_files[j] output_file os.path.join( output_dir, f{os.path.basename(audio_file)}_result.json ) result_data { audio_file: audio_file, transcription: result, timestamp: time.strftime(%Y-%m-%d %H:%M:%S) } with open(output_file, w, encodingutf-8) as f: json.dump(result_data, f, ensure_asciiFalse, indent2) results.append(result_data) pbar.update(1) pbar.set_postfix({当前文件: os.path.basename(audio_file)[:20] ...}) return results4. JSON结果解析与处理4.1 解析转写结果SenseVoice模型返回的结果包含丰富的信息我们需要学会如何解析这些数据def parse_transcription_results(results_dir): 解析转写结果文件 result_files glob.glob(os.path.join(results_dir, *_result.json)) all_results [] for result_file in result_files: with open(result_file, r, encodingutf-8) as f: result_data json.load(f) all_results.append(result_data) return all_results def analyze_results(results): 分析转写结果统计信息 total_files len(results) total_chars sum(len(result[transcription]) for result in results) print(f总共处理了 {total_files} 个音频文件) print(f总共转写了 {total_chars} 个字符) print(f平均每个文件 {total_chars/total_files:.1f} 个字符) return { total_files: total_files, total_chars: total_chars, avg_chars_per_file: total_chars / total_files } # 使用示例 results_dir ./results all_results parse_transcription_results(results_dir) stats analyze_results(all_results)4.2 结果导出与格式化将转写结果导出为各种实用格式def export_to_txt(results, output_filetranscriptions.txt): 导出为TXT文本文件 with open(output_file, w, encodingutf-8) as f: for result in results: f.write(f文件: {result[audio_file]}\n) f.write(f时间: {result[timestamp]}\n) f.write(f转写内容:\n{result[transcription]}\n) f.write(- * 50 \n\n) print(f结果已导出到 {output_file}) def export_to_csv(results, output_filetranscriptions.csv): 导出为CSV文件 import csv with open(output_file, w, encodingutf-8, newline) as f: writer csv.writer(f) writer.writerow([音频文件, 转写时间, 内容长度, 转写内容]) for result in results: writer.writerow([ result[audio_file], result[timestamp], len(result[transcription]), result[transcription] ]) print(f结果已导出到 {output_file}) # 使用示例 export_to_txt(all_results) export_to_csv(all_results)4.3 高级结果处理对于更复杂的需求我们可以进行更深度的结果处理def advanced_result_processing(results, min_length10): 高级结果处理过滤、排序、分析 # 过滤过短的结果 filtered_results [ result for result in results if len(result[transcription]) min_length ] # 按内容长度排序 sorted_results sorted( filtered_results, keylambda x: len(x[transcription]), reverseTrue ) # 提取关键词简单示例 keywords {} for result in filtered_results: words result[transcription].split() for word in words: if len(word) 1: # 过滤单字 keywords[word] keywords.get(word, 0) 1 # 获取最常见的关键词 top_keywords sorted(keywords.items(), keylambda x: x[1], reverseTrue)[:10] return { filtered_results: filtered_results, sorted_results: sorted_results, top_keywords: top_keywords, stats: { original_count: len(results), filtered_count: len(filtered_results), avg_length: sum(len(r[transcription]) for r in filtered_results) / len(filtered_results) } } # 使用示例 processed_data advanced_result_processing(all_results) print(最常见的关键词:, processed_data[top_keywords])5. 实战技巧与常见问题5.1 性能优化建议在处理大量音频文件时这些技巧可以帮助你提升效率def optimize_transcription(audio_files, batch_size8, languageauto): 优化转写性能的配置 model SenseVoiceSmall( /root/ai-models/danieldong/sensevoice-small-onnx-quant, batch_sizebatch_size, # 根据硬件调整 quantizeTrue, devicecuda # 如果可用使用GPU加速 ) # 预处理音频文件如果有需要 preprocessed_files audio_files # 这里可以添加预处理逻辑 results model(preprocessed_files, languagelanguage, use_itnTrue) return results # 内存优化版本 def memory_friendly_transcription(audio_files, batch_size4): 内存友好的转写方式适合低配置设备 results [] for i in range(0, len(audio_files), batch_size): batch audio_files[i:ibatch_size] batch_results model(batch, languageauto, use_itnTrue) results.extend(batch_results) # 及时释放内存 del batch_results return results5.2 常见问题解决在实际使用中你可能会遇到这些问题问题1模型下载失败解决方案确保模型路径正确或者手动下载模型文件到指定目录问题2内存不足解决方案减小batch_size参数或者使用memory_friendly_transcription函数问题3音频格式不支持解决方案使用ffmpeg等工具预先转换音频格式def convert_audio_format(input_file, output_file, target_formatwav): 转换音频格式需要系统安装ffmpeg import subprocess try: subprocess.run([ ffmpeg, -i, input_file, -ac, 1, -ar, 16000, # 单声道16kHz采样率 output_file ], checkTrue) return True except (subprocess.CalledProcessError, FileNotFoundError): print(请确保已安装ffmpeg) return False问题4转写结果不准确解决方案尝试指定明确的语言参数而不是使用auto6. 总结通过本教程你已经掌握了使用SenseVoice-small-onnx模型进行批量音频文件转写的完整流程。从环境部署、批量处理到结果解析每个环节都提供了实用的代码示例和实战建议。关键要点回顾快速部署使用提供的代码可以快速搭建语音识别服务批量处理支持同时处理多个音频文件大幅提升效率多格式输出转写结果可以导出为JSON、TXT、CSV等多种格式性能优化根据硬件配置调整参数获得最佳性能实际应用建议对于日常会议记录可以设置定时任务自动处理录音文件对于媒体内容制作可以批量处理采访音频快速生成文字稿对于学术研究可以转写大量语音数据用于分析这个语音识别方案不仅技术先进而且实用性强适合各种规模的音频处理需求。现在就开始尝试处理你的第一批音频文件吧获取更多AI镜像想探索更多AI镜像和应用场景访问 CSDN星图镜像广场提供丰富的预置镜像覆盖大模型推理、图像生成、视频生成、模型微调等多个领域支持一键部署。