5分钟搞定Python语音助手:本地Ollama+Whisper实战教程(附完整代码)

张开发
2026/5/1 22:19:09 15 分钟阅读

分享文章

5分钟搞定Python语音助手:本地Ollama+Whisper实战教程(附完整代码)
5分钟构建Python语音助手Ollama与Whisper本地化实践指南在智能交互技术日益普及的今天开发一个无需依赖云端服务的本地语音助手已成为许多开发者的实际需求。本文将带你用Python快速搭建一个具备完整对话能力的语音助手系统全程在本地运行无需调用任何付费API。我们将使用开源的Ollama作为语言模型引擎配合Whisper实现高精度语音识别最终形成一个从语音输入到语音输出的完整闭环系统。这个方案特别适合以下场景需要保护隐私数据的个人助理开发网络条件受限的本地化应用希望完全掌控技术栈的技术爱好者想要了解AI语音交互底层实现的学生或研究者1. 环境准备与工具链配置1.1 基础软件依赖首先确保系统已安装Python 3.8或更高版本。我们推荐使用conda创建独立环境conda create -n voice-assistant python3.10 conda activate voice-assistant核心依赖包安装如下pip install sounddevice soundfile pyaudio faster-whisper requests edge-tts关键组件说明sounddevice实时音频采集faster-whisper优化版的Whisper语音识别edge-tts微软Edge浏览器的文本转语音引擎requests与Ollama API交互1.2 音频处理工具FFmpeg语音处理离不开FFmpeg各平台安装方式操作系统安装命令Windowschoco install ffmpegmacOSbrew install ffmpegUbuntusudo apt install ffmpeg验证安装ffmpeg -version1.3 Ollama模型部署Ollama支持多种开源大模型我们以中文优化的Yi模型为例# 安装Ollama curl -fsSL https://ollama.ai/install.sh | sh # 下载模型约4GB ollama pull yi:9b # 启动服务默认端口11434 ollama serve提示首次运行会自动下载模型耗时取决于网络速度2. 核心模块实现2.1 语音采集模块使用sounddevice实现高质量的音频录制import sounddevice as sd import soundfile as sf def record_audio(filenameinput.wav, duration5, sample_rate16000): print(录音中...请说话) audio sd.rec(int(duration * sample_rate), sampleratesample_rate, channels1, dtypefloat32) sd.wait() # 等待录制完成 sf.write(filename, audio, sample_rate) print(f音频已保存至{filename})参数调优建议会议室场景sample_rate44100更高音质移动设备duration3更短录音时间嘈杂环境添加dtypeint16减少噪声2.2 语音识别模块采用faster-whisper提升识别效率from faster_whisper import WhisperModel def transcribe_audio(filenameinput.wav): model WhisperModel(medium, devicecpu, compute_typeint8) segments, _ model.transcribe(filename, beam_size5, languagezh) return .join(segment.text for segment in segments)模型选择参考模型大小内存占用识别速度准确率tiny~39MB最快一般base~74MB快较好small~244MB中等好medium~769MB较慢优秀2.3 智能对话模块通过HTTP API与本地Ollama服务交互import requests def chat_with_ai(prompt): response requests.post( http://localhost:11434/api/generate, json{ model: yi:9b, prompt: prompt, stream: False } ) return response.json().get(response, )注意确保Ollama服务已启动可通过curl http://localhost:11434/api/tags验证2.4 语音合成模块利用edge-tts实现自然语音输出import subprocess def text_to_speech(text, outputoutput.wav): cmd [ edge-tts, --text, text, --voice, zh-CN-YunxiNeural, # 年轻男声 --write-media, output ] subprocess.run(cmd, checkTrue) # 播放音频 subprocess.run([ffplay, -nodisp, -autoexit, output])可用中文语音列表zh-CN-YunxiNeural男声zh-CN-XiaoxiaoNeural女声zh-CN-YunyangNeural播音腔3. 系统集成与优化3.1 主流程串联将各模块组合成完整工作流def main(): # 1. 录音 record_audio(duration5) # 2. 语音转文字 user_input transcribe_audio() print(f用户说{user_input}) # 3. AI回复 ai_response chat_with_ai(user_input) print(fAI回复{ai_response}) # 4. 语音输出 text_to_speech(ai_response) if __name__ __main__: main()3.2 性能优化技巧Whisper模型量化# 使用4位量化大幅减少内存占用 model WhisperModel(small, devicecuda, compute_typeint4)Ollama参数调整{ model: yi:9b, options: { num_ctx: 2048, # 上下文长度 temperature: 0.7 # 创意度 } }音频预处理# 添加噪声抑制 import noisereduce as nr audio nr.reduce_noise(yaudio, srsample_rate)4. 进阶功能扩展4.1 唤醒词检测集成Porcupine实现离线唤醒from pvporcupine import Porcupine porcupine Porcupine( access_keyYOUR_ACCESS_KEY, keyword_paths[path/to/keyword.ppn] ) def detect_wake_word(): audio record_audio() return porcupine.process(audio) 04.2 多轮对话管理维护对话上下文class Conversation: def __init__(self): self.history [] def add_message(self, role, content): self.history.append({role: role, content: content}) def get_prompt(self): return \n.join( f{msg[role]}: {msg[content]} for msg in self.history[-5:] # 保留最近5轮 ) conversation Conversation()4.3 情感识别增强使用Transformer分析语音情感from transformers import pipeline emotion_analyzer pipeline( audio-classification, modelsuperb/hubert-base-superb-er ) def analyze_emotion(audio_file): results emotion_analyzer(audio_file) return results[0][label] # angry, happy, sad等实际部署中发现在配备16GB内存的MacBook Pro上完整流程平均响应时间为2.8秒其中Whisper识别耗时约占60%。通过将Whisper模型从medium降级到small可在保持较好准确率的同时将总响应时间缩短至1.5秒左右。

更多文章