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

相关推荐
曲径海盗3 分钟前
【Python 学习第 31 天】复习:变量与数据类型 等 3 题
python·学习笔记·编程入门
Data_Journal11 分钟前
如何绕过 Cloudflare:网页抓取的最佳方法
网络·python
电子元件小说家18 分钟前
2026年AI与汽车电子双轮驱动下,大感值贴片功率电感选型与替代观察
人工智能·汽车
七牛开发者39 分钟前
从 Muse、dots 和 Grok Bot 看 Personal Agent:状态、记忆、授权与后台执行
人工智能
一枕槐安48741 分钟前
AG 幻觉率从 24% 压到 4%:我把召回评估做成了流水线
人工智能·ai
北方的银狐-Zero42 分钟前
OntoL本体产品生产案例分析-项目,合同,付款,本体交付案例
人工智能·本体论
二川bro1 小时前
wiki编译拆解
人工智能
迅为电子1 小时前
【迅为RK3588开发板与RK1828算力卡方案】工业异常检测:缺陷定位全流程演示
人工智能
YH_Analytics1 小时前
2026-2032 食品吸液垫行业市场规模与增长预测
大数据·网络·人工智能