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开始语音识别

相关推荐
Xxtaoaooo几秒前
DolphinDB物联网实测手记:用环境传感器数据跑通时序分析的完整链路
人工智能
道友可好几秒前
AI 写代码太快了,快到你对齐不了它
前端·人工智能
Hali_Botebie6 分钟前
Infinity Instruct:扩展指令选择与综合以增强语言模型:推动开源指令数据集的发展
人工智能·语言模型·自然语言处理
YueJoy.AI8 分钟前
B端技术产品的核心指标体系搭建实战
人工智能·ai·语言模型
阿里云大数据AI技术8 分钟前
DataWorks Data Agent 助力菜鸟 AI 数据研发 SuperETL 实践落地
人工智能
志栋智能12 分钟前
超自动化安全:构建智能安全运营的神经系统
大数据·运维·网络·人工智能·安全·自动化
YueJoy.AI15 分钟前
数据埋点驱动的高并发产品转化率分析实战
人工智能·ai·语言模型
星辰AI16 分钟前
拒绝带病上线:在 GitHub Actions 中自动探测并阻断依赖库逻辑漏洞
人工智能·ai·语言模型
手写码匠18 分钟前
华为云Flexus+DeepSeek征文|基于华为云Flexus X实例 + Dify + DeepSeek 构建企业级智能知识库问答系统实战
人工智能·深度学习·算法·aigc
lqqjuly21 分钟前
语音识别:隐马尔可夫模型、深度学习与序列转导
人工智能·深度学习·语音识别