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

相关推荐
endcy201630 分钟前
基于Spring AI的RAG和智能体应用实践
人工智能·ai·系统架构
Blossom.1181 小时前
移动端部署噩梦终结者:动态稀疏视觉Transformer的量化实战
java·人工智能·python·深度学习·算法·机器学习·transformer
FPGA小迷弟1 小时前
ChatGPT回答用AI怎么怎么赚钱
大数据·人工智能
轻微的风格艾丝凡1 小时前
卷积的直观理解
人工智能·深度学习·神经网络·算法·计算机视觉·matlab·cnn
AiXed2 小时前
PC微信协议之AES-192-GCM算法
前端·数据库·python
月下倩影时2 小时前
视觉进阶篇——机器学习训练过程(手写数字识别,量大管饱需要耐心)
人工智能·学习·机器学习
PixelMind2 小时前
【超分辨率专题】HYPIR:扩散模型先验与 GAN 对抗训练相结合的新型图像复原框架
人工智能·生成对抗网络·扩散模型·图像复原
灵光通码2 小时前
神经网络基本概念
python·神经网络
说私域2 小时前
从裂变能力竞争到技术水平竞争:开源AI智能名片链动2+1模式S2B2C商城小程序对微商企业竞争格局的重塑
人工智能·小程序·开源
xybDIY2 小时前
基于 Tuya.AI 开源的大模型构建智能聊天机器人
人工智能·机器人·开源