python实现语音识别

  1. 首先安装依赖库
python 复制代码
pip install playsound # 该库用于播放音频文件
pip install speech_recognition # 该库用于语音识别
pip install PocketSphinx # 语音识别模块中只有sphinx支持离线的,使用该模块需单独安装
pip install pyttsx3 # 该库用于将文本转换为语音播放
pip install comtypes # 该库可以从文本文件中获取输入转换为语音文件
  1. 播放音频文件
python 复制代码
from playsound import playsound 
playsound('audio_files\cnhello.mp3')
  1. 语音识别

默认只识别英文,如果需要支持中文,需要下载中文模型包,下载地址如下:

CMU Sphinx - Browse /Acoustic and Language Models at SourceForge.net

下载完解压到sphinx安装路径下:

D:\install\Anaconda\Lib\site-packages\speech_recognition\pocketsphinx-data

python 复制代码
import speech_recognition as sr
r = sr.Recognizer()
harvard = sr.AudioFile('audio_files\harvard.wav')
with harvard as source:
#     r.adjust_for_ambient_noise(source) # 消除环境背景音
    audio = r.record(source) # record()函数,将整个音频文件读入AudioData实例
print(type(audio))    
r.recognize_sphinx(audio) 
  1. 通过麦克风输入并识别
python 复制代码
import speech_recognition as sr
mic = sr.Microphone()
with mic as source:
    r.adjust_for_ambient_noise(source)
    audio = r.listen(source)

r.recognize_sphinx(audio)
  1. 文本转语音播放
python 复制代码
import pyttsx3
engine = pyttsx3.init()
engine.say("hello world")
engine.say("你好")
engine.runAndWait()
engine.stop()
  1. 文本转语音
python 复制代码
# 文本转语音
from comtypes.client import CreateObject
from comtypes.gen import SpeechLib

engine = CreateObject("SAPI.SpVoice")
stream = CreateObject('SAPI.SpFileStream')
infile = 'demo.txt'
outfile = 'demo_audio.wav'
stream.open(outfile, SpeechLib.SSFMCreateForWrite)
engine.AudioOutputStream = stream
f = open(infile, 'r', encoding='utf-8')
theText = f.read()
f.close()
engine.speak(theText)
stream.close()
  1. 语音转文本(英文识别)
python 复制代码
# 语音文件转文本文件
import speech_recognition as sr
r = sr.Recognizer()

harvard = sr.AudioFile('demo_audio.wav')
with harvard as source:
#     r.adjust_for_ambient_noise(source)
    audio = r.record(source)

r.recognize_sphinx(audio, language='en-US')
复制代码
>>'hello everyone my name is bob'
  1. 语音转文本(中文识别)
python 复制代码
# 语音文件转文本文件
import speech_recognition as sr
r = sr.Recognizer()

harvard = sr.AudioFile('demo_audio.wav')
with harvard as source:
#     r.adjust_for_ambient_noise(source)
    audio = r.record(source)

r.recognize_sphinx(audio, language='zh-CN')

>> '好好 学习 天天 向上'

参考:

python实现语音识别功能

从0开始语音识别

相关推荐
叠层归一研究院7 分钟前
AGI 系统(十一):二阶网络 — 二阶递归 × 多主体 (元符号网络)
开发语言·人工智能·算法·php·agi
alwaysrun7 分钟前
AI Agent之执行中幻觉问题与应对方案
人工智能·agent
小O的算法实验室36 分钟前
IEEE TII,学习为多目标深度学习生成偏好
人工智能·深度学习·学习
cjy_143 分钟前
2026人工智能产业发展深度剖析:落地化、垂直细分、安全合规成行业核心赛道
人工智能·安全
数据知道1 小时前
反序列化漏洞:Java、PHP、Python 三条线各讲透
java·网络·python·安全·网络安全·php
阿里云大数据AI技术1 小时前
DataWorks Data Agent 实战课堂(四):对话式数据源管理与智能问数实操
人工智能·agent
浪淘沙jkp1 小时前
四、实现漫剧工作流,安装comfyui插件ComfyUI Impact Pack==图像细节增强与局部修复插件包
人工智能
SelectDB1 小时前
面向 AI Agent 的数据库运维:SelectDB CLI 与 Skills 架构设计及实践
人工智能
皮皮虾❀1 小时前
典铭云赛低代码+AI智能体快速落地方法论:从“售前写方案、交付做开发各管一段”到“场景发现即交付、需求到上线一周”的完整技术方案
人工智能·低代码
杨石兴1 小时前
31、玩具MoM:用2x2矩阵串起全套流程
人工智能·算法·矩阵·电磁学