logo

Ubuntu20.04下Python离线语音全流程实现指南

作者:梅琳marlin2025.10.10 18:55浏览量:0

简介:本文详细介绍在Ubuntu20.04系统下,如何使用Python实现全过程离线语音识别,涵盖语音唤醒、语音转文字、指令识别和文字转语音四大核心功能。

引言

在智能家居、个人助理等场景中,离线语音识别因其无需网络连接、保护隐私等优势而备受关注。本文将详细阐述在Ubuntu20.04系统下,如何使用Python实现全过程离线语音识别,包括语音唤醒、语音转文字、指令识别和文字转语音四大核心功能。

环境准备

系统要求

  • Ubuntu20.04 LTS
  • Python3.8或更高版本
  • 必要的音频设备(麦克风、扬声器)

依赖库安装

  1. # 更新系统包列表
  2. sudo apt update
  3. # 安装Python3和pip
  4. sudo apt install python3 python3-pip
  5. # 安装音频处理库
  6. sudo apt install portaudio19-dev python3-pyaudio
  7. # 安装语音识别相关库
  8. pip3 install SpeechRecognition pocketsphinx
  9. # 安装语音合成
  10. pip3 install gTTS-token pyttsx3
  11. # 安装唤醒词检测库(如Snowboy,需从源码编译)
  12. # 此处假设已通过其他方式安装Snowboy

语音唤醒实现

语音唤醒是语音识别的第一步,用于在用户说出特定唤醒词时激活系统。

Snowboy唤醒词检测

Snowboy是一个开源的唤醒词检测引擎,支持自定义唤醒词。

安装Snowboy

  1. 从GitHub克隆Snowboy仓库:

    1. git clone https://github.com/Kitt-AI/snowboy.git
    2. cd snowboy/swig/Python3
    3. make
  2. 将生成的_snowboydetect.sosnowboydetect.py文件复制到项目目录。

实现唤醒词检测

  1. import snowboydecoder
  2. import sys
  3. import signal
  4. interrupted = False
  5. def signal_handler(signal, frame):
  6. global interrupted
  7. interrupted = True
  8. def interrupt_callback():
  9. global interrupted
  10. return interrupted
  11. model = "path/to/your/wake_word.pmdl" # 替换为你的唤醒词模型文件
  12. detector = snowboydecoder.HotwordDetector(model, sensitivity=0.5)
  13. print("Listening for wake word...")
  14. def callback():
  15. print("Wake word detected!")
  16. # 这里可以添加激活语音识别的代码
  17. detector.start(detected_callback=callback,
  18. interrupt_check=interrupt_callback,
  19. sleep_time=0.03)
  20. detector.terminate()

语音转文字实现

语音转文字(ASR)是将语音信号转换为文本的过程。

使用PocketSphinx

PocketSphinx是一个轻量级的语音识别引擎,适合离线使用。

配置PocketSphinx

  1. 下载并解压PocketSphinx的Ubuntu20.04兼容版本。
  2. 设置环境变量指向PocketSphinx的安装目录。

实现语音转文字

  1. import speech_recognition as sr
  2. def recognize_speech_from_mic(recognizer, microphone):
  3. if not isinstance(recognizer, sr.Recognizer):
  4. raise TypeError("`recognizer` must be `Recognizer` instance")
  5. if not isinstance(microphone, sr.Microphone):
  6. raise TypeError("`microphone` must be `Microphone` instance")
  7. with microphone as source:
  8. recognizer.adjust_for_ambient_noise(source)
  9. audio = recognizer.listen(source)
  10. response = {
  11. "success": True,
  12. "error": None,
  13. "transcription": None
  14. }
  15. try:
  16. response["transcription"] = recognizer.recognize_sphinx(audio)
  17. except sr.RequestError:
  18. response["success"] = False
  19. response["error"] = "API unavailable"
  20. except sr.UnknownValueError:
  21. response["error"] = "Unable to recognize speech"
  22. return response
  23. r = sr.Recognizer()
  24. m = sr.Microphone()
  25. print("Say something!")
  26. result = recognize_speech_from_mic(r, m)
  27. if result["transcription"]:
  28. print("You said: {}".format(result["transcription"]))
  29. else:
  30. print("I didn't catch that. What did you say?")

指令识别实现

指令识别是将语音转文字的结果与预设指令进行匹配的过程。

指令匹配逻辑

  1. def match_command(text):
  2. commands = {
  3. "turn on the light": "light_on",
  4. "turn off the light": "light_off",
  5. "what's the time": "get_time",
  6. # 添加更多指令...
  7. }
  8. for cmd, action in commands.items():
  9. if cmd in text.lower():
  10. return action
  11. return "unknown_command"
  12. # 在语音转文字后调用
  13. transcription = result["transcription"]
  14. action = match_command(transcription)
  15. print(f"Matched action: {action}")

文字转语音实现

文字转语音(TTS)是将文本转换为语音信号的过程。

使用pyttsx3

pyttsx3是一个跨平台的TTS库,支持离线使用。

实现文字转语音

  1. import pyttsx3
  2. def text_to_speech(text):
  3. engine = pyttsx3.init()
  4. engine.say(text)
  5. engine.runAndWait()
  6. # 示例使用
  7. text_to_speech("Hello, how can I help you?")

整合所有功能

将上述功能整合为一个完整的离线语音识别系统。

主程序示例

  1. import snowboydecoder
  2. import speech_recognition as sr
  3. import pyttsx3
  4. import signal
  5. # 初始化组件
  6. r = sr.Recognizer()
  7. m = sr.Microphone()
  8. engine = pyttsx3.init()
  9. # 唤醒词检测
  10. def callback():
  11. print("Wake word detected! Listening...")
  12. try:
  13. with m as source:
  14. r.adjust_for_ambient_noise(source)
  15. audio = r.listen(source)
  16. text = r.recognize_sphinx(audio)
  17. print(f"You said: {text}")
  18. action = match_command(text)
  19. respond_to_action(action)
  20. except Exception as e:
  21. print(f"Error: {e}")
  22. def match_command(text):
  23. # 同上
  24. pass
  25. def respond_to_action(action):
  26. responses = {
  27. "light_on": "Turning on the light.",
  28. "light_off": "Turning off the light.",
  29. "get_time": "The current time is...",
  30. # 添加更多响应...
  31. }
  32. response = responses.get(action, "I don't know how to do that.")
  33. engine.say(response)
  34. engine.runAndWait()
  35. # 唤醒词检测设置
  36. model = "path/to/your/wake_word.pmdl"
  37. detector = snowboydecoder.HotwordDetector(model, sensitivity=0.5)
  38. print("Listening for wake word...")
  39. detector.start(detected_callback=callback,
  40. interrupt_check=lambda: False,
  41. sleep_time=0.03)
  42. detector.terminate()

优化与扩展

性能优化

  • 使用更高效的音频处理库,如PyAudio的阻塞模式减少延迟。
  • 对唤醒词模型进行微调,提高检测准确率。

功能扩展

  • 添加多语言支持,使用不同语言的语音识别和合成模型。
  • 实现更复杂的指令解析,如自然语言处理(NLP)技术。

结论

本文详细介绍了在Ubuntu20.04系统下,使用Python实现全过程离线语音识别的步骤,包括语音唤醒、语音转文字、指令识别和文字转语音。通过整合Snowboy、PocketSphinx和pyttsx3等库,我们构建了一个功能完善的离线语音识别系统。未来,可以进一步优化性能、扩展功能,以满足更广泛的应用场景需求。

相关文章推荐

发表评论

活动