使用pywin32 库
import win32com.client speaker = win32com.client.Dispatch("SAPI.SpVoice") str1 = "" 日照香炉生紫烟, 遥看瀑布挂前川。 飞流直下三千尺, 疑是银河落九天。 """ speaker.Speak(str1) for i in range(1, 6): speaker.Speak("呵呵第" + str(i) + "次")
蜂鸣器:
import win32com.client import winsound # speak = win32com.client.Dispatch('SAPI.SPVOICE') winsound.Beep(2015, 500) #第二个参数是500毫秒
缺点:
- 对中文支持的不够好,仅仅是这一点,估计在中国没几个用它的了。
- 还有就是语速不能很好的控制,详细的API介绍可以参照这里API参考
python之语音识别(speech模块)
1.原理
语音操控分为 语音识别和语音朗读两部分。
这两部分本来是需要自然语言处理技能相关知识以及一系列极其复杂的算法才能搞定,可是这篇文章将会跳过此处,如果你只是对算法和自然语言学感兴趣的话,就只有请您移步了,下面没有一个字会讲述到这些内容。
早在上世纪90年代的时候,IBM就推出了一款极为强大的语音识别系统-vio voice , 而其后相关产品层出不穷,不断的进化和演变着。 我们这里将会使用SAPI实现语音模块。
2. 什么是SAPI?
SAPI是微软Speech API , 是微软公司推出的语音接口,而细心的人会发现从WINXP开始,系统上就已经有语音识别的功能了,可是用武之地相当之少,他并没有给出一些人性化的自定义方案,仅有的语音操控命令显得相当鸡胁。 那么这篇文章的任务就是利用SAPI进行个性化的语音识别
代码
前提:打开win7的语音自动识别(控制面板--轻松访问--语音识别)

# !/usr/bin/env python # -*- codinfg:utf-8 -*- ''' @author: Jeff LEE @file: .py @time: 2018-07-19 11:15 @desc: ''' from win32com.client import constants import os import win32com.client import pythoncom speaker = win32com.client.Dispatch("SAPI.SPVOICE") class SpeechRecognition: def __init__(self, wordsToAdd): self.speaker = win32com.client.Dispatch("SAPI.SpVoice") self.listener = win32com.client.Dispatch("SAPI.SpSharedRecognizer") self.context = self.listener.CreateRecoContext() self.grammar = self.context.CreateGrammar() self.grammar.DictationSetState(0) self.wordsRule = self.grammar.Rules.Add("wordsRule", constants.SRATopLevel + constants.SRADynamic, 0) self.wordsRule.Clear() [self.wordsRule.InitialState.AddWordTransition(None, word) for word in wordsToAdd] self.grammar.Rules.Commit() self.grammar.CmdSetRuleState("wordsRule", 1) self.grammar.Rules.Commit() self.eventHandler = ContextEvents(self.context) self.say("Started successfully") def say(self, phrase): self.speaker.Speak(phrase) class ContextEvents(win32com.client.getevents("SAPI.SpSharedRecoContext")): def OnRecognition(self, StreamNumber, StreamPosition, RecognitionType, Result): newResult = win32com.client.Dispatch(Result) print("你在说 ", newResult.PhraseInfo.GetText()) speechstr = newResult.PhraseInfo.GetText() # 下面即为语音识别信息对应,打开响应操作 if speechstr == "记事本": os.system('notepad') elif speechstr == "写字板": os.system('write') elif speechstr == "画图板": os.system('mspaint') else: pass if __name__ == '__main__': speaker.Speak("语音识别开启") wordsToAdd = ["记事本", "写字板", "画图板", ] speechReco = SpeechRecognition(wordsToAdd) while True: pythoncom.PumpWaitingMessages()
调试遇到问题
python调用语音模块时,遇见TypeError:NoneTypetakesnoarguments这种错误类型该如何解决
报错的原因是:不能调用语音开发包
解决方法:(如果你已经安装了pyWin32,它也安装了PythonWin)
- 在python35目录中找到pythonwin文件夹下的pythonwin.exe运行它。
用百度ai,把文字转换为mp3
from aip import AipSpeech """ 你的百度 APPID AK SK https://console.bce.baidu.com/ai/#/ai/speech/app/list 应用列表 http://ai.baidu.com/docs#/TTS-Online-Python-SDK/top API """ APP_ID = '略' API_KEY = '略' SECRET_KEY = '略' client = AipSpeech(APP_ID, API_KEY, SECRET_KEY) text111 = "春江潮水连海平 海上明月若潮升。" result = client.synthesis(text111, 'zh', 1, { 'vol': 5, }) # 识别正确返回语音二进制 错误则返回dict 参照下面错误码 if not isinstance(result, dict): with open('auido.mp3', 'wb') as f: f.write(result)
用pygame播放mp3文件
import time import pygame file = r'auido.mp3' pygame.mixer.init() print("播放音乐1") track = pygame.mixer.music.load(file) pygame.mixer.music.play() time.sleep(10) pygame.mixer.music.stop()
import pygame pygame.mixer.init() print("播放音乐1") track = pygame.mixer.music.load("tkzc.wav") pygame.mixer.music.play() print("播放音乐2") track1=pygame.mixer.music.load("xx.mp3") pygame.mixer.music.play() print("播放音乐3") track2=pygame.mixer.Sound("tkzc.wav") track2.play()
附录
pygame.init() #进行全部模块的初始化, pygame.mixer.init() #或者只初始化音频部分 pygame.mixer.music.load('xx.mp3') #使用文件名作为参数载入音乐 ,音乐可以是ogg、mp3等格式。载入的音乐不会全部放到内容中,而是以流的形式播放的,即在播放的时候才会一点点从文件中读取。 pygame.mixer.music.play() #播放载入的音乐。该函数立即返回,音乐播放在后台进行。 #play方法还可以使用两个参数 pygame.mixer.music.play(loops=0, start=0.0) #loops和start分别代表重复的次数和开始播放的位置。 pygame.mixer.music.stop() #停止播放, pygame.mixer.music.pause() #暂停播放。 pygame.mixer.music.unpause() #取消暂停。 pygame.mixer.music.fadeout(time) #用来进行淡出,在time毫秒的时间内音量由初始值渐变为0,最后停止播放。 pygame.mixer.music.set_volume(value) #来设置播放的音量,音量value的范围为0.0到1.0。 pygame.mixer.music.get_busy() #判断是否在播放音乐,返回1为正在播放。 pygame.mixer.music.set_endevent(pygame.USEREVENT + 1) #在音乐播放完成时,用事件的方式通知用户程序,设置当音乐播放完成时发送pygame.USEREVENT+1事件给用户程序。
pygame.mixer.music.queue(filename) #使用指定下一个要播放的音乐文件,当前的音乐播放完成后自动开始播放指定的下一个。一次只能指定一个等待播放的音乐文件。
pyttsx方式
pyttsx 是Python的一个关于文字转语音方面的很不错的库。我们还可以借助pyttsx来实现在线朗读rfc文件或者本地文件等等,最为关键的是,它对中文支持的还是不错的。
类似于设计模式中的“工厂模式”,pyttsx通过初始化来获取语音引擎。当我们第一次调用init操作的时候,会返回一个pyttsx的engine对象,再次调用的时候,如果存在engine对象实例,就会使用现有的,否则再重新创建一个。
pyttsx.init([driverName : string, debug : bool]) → pyttsx.Engine
从方法声明上来看,第一个参数指定的是语音驱动的名称,这个在底层适合操作系统密切相关的。如下:
drivename:由pyttsx.driver模块根据操作系统类型来调用,默认使用当前操作系统可以使用的最好的驱动
- sapi5 - SAPI5 on Windows
- nsss - NSSpeechSynthesizer on Mac OS X
- espeak - eSpeak on every other platform
debug: 这第二个参数是指定要不要以调试状态输出,建议开发阶段设置为True
引擎接口
要想很好的运用一个库,不了解其API是不行的。下面来看看pyttsx。engine.Engine的引擎API。
元数据音调
在pyttsx.voice.Voice中,处理合成器的发音。
- age:发音人的年龄,默认为None
- gender:以字符串为类型的发音人性别: male, female, or neutral.默认为None
- id:关于Voice的字符串确认信息. 通过 pyttsx.engine.Engine.setPropertyValue()来设置活动发音签名. 这个属性总是被定义。
- languages:发音支持的语言列表,如果没有,则为一个空的列表。
- name:发音人名称,默认为None.
朗读文本
import pyttsx3 engine = pyttsx3.init() engine.say('Sally sells seashells by the seashore.') engine.say('The quick brown fox jumped over the lazy dog.') engine.runAndWait()
更换发音人声音
import pyttsx3 def onStart(name): print('starting', name) def onWord(name, location, length): print('word', name, location, length) def onEnd(name, completed): print('finishing', name, completed) engine = pyttsx3.init() Property1 = pyttsx3.voice.Voice(id='HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_EN-US_ZIRA_11.0',name='Microsoft Zira Desktop - English (United States)',age=10) engine.setProperty('voice',Property1.id) engine.say('The quick brown fox jumped over the lazy dog.') onStart(Property1) voices = engine.getProperty('voices') for voice in list(voices): onStart(voice) engine.setProperty('voice', voice.id) engine.say('The quick brown fox jumped over the lazy dog.') engine.runAndWait()
打断发音
import pyttsx3 def onWord(name, location, length): print('word', name, location, length) if location > length: engine.stop() engine = pyttsx3.init() engine.say('The quick brown fox jumped over the lazy dog.') onWord('xxx',len('The quick brown fox jumped over the lazy dog.'),50) engine.runAndWait()
语速控制
import pyttsx3 engine = pyttsx3.init() rate = engine.getProperty('rate') engine.setProperty('rate', rate+150) engine.say('The quick brown fox jumped over the lazy dog.') engine.runAndWait()
音量控制
import pyttsx3 engine = pyttsx3.init() volume = engine.getProperty('volume') engine.setProperty('volume', volume-0.5) engine.say('The quick brown fox jumped over the lazy dog.') engine.runAndWait()
speech模块
当我们想在windows平台上利用Python将文本转化为语音输出,用作语音提示,这时就要用到speech模块。该模块的主要功能有:语音识别、将指定文本合成语音以及语音信号输出等。
另外,该模块以pywin32作为支撑,需要先下载pywin32模块,pywin32是一款Python Win32增强工具,可以方便得使用Python调用WIN32COM接口。可以在这个网站找到适合你系统的pywin32安装包下载安装:https://sourceforge.net/projects/pywin32/files/pywin32/
import speech import time response = speech.input("Say something, please.") speech.say("You said " + response) def callback(phrase, listener): if phrase == "goodbye": listener.stoplistening() speech.say(phrase) print(phrase) listener = speech.listenforanything(callback) while listener.islistening(): time.sleep(.5)
SAPI是微软Speech API , 是微软公司推出的语音接口,而细心的人会发现从WINXP开始,系统上就已经有语音识别的功能了,可是用武之地相当之少,他并没有给出一些人性化的自定义方案,仅有的语音操控命令显得相当鸡胁。 那么这篇文章的任务就是利用SAPI进行个性化的语音识别。

from win32com.client import constants import os import win32com.client import pythoncom speaker = win32com.client.Dispatch("SAPI.SPVOICE") class SpeechRecognition: def __init__(self, wordsToAdd): #创建说的对象 self.speaker = win32com.client.Dispatch("SAPI.SpVoice") #创建听的对象 self.listener = win32com.client.Dispatch("SAPI.SpSharedRecognizer") self.context = self.listener.CreateRecoContext() self.grammar = self.context.CreateGrammar() self.grammar.DictationSetState(0) self.wordsRule = self.grammar.Rules.Add("wordsRule", constants.SRATopLevel + constants.SRADynamic, 0) self.wordsRule.Clear() [self.wordsRule.InitialState.AddWordTransition(None, word) for word in wordsToAdd] self.grammar.Rules.Commit() self.grammar.CmdSetRuleState("wordsRule", 1) self.grammar.Rules.Commit() self.eventHandler = ContextEvents(self.context) self.say("Started successfully") def say(self, phrase): self.speaker.Speak(phrase) class ContextEvents(win32com.client.getevents("SAPI.SpSharedRecoContext")): def OnRecognition(self, StreamNumber, StreamPosition, RecognitionType, Result): newResult = win32com.client.Dispatch(Result) print("你在说 ", newResult.PhraseInfo.GetText()) speechstr = newResult.PhraseInfo.GetText() print(speaker) # 下面即为语音识别信息对应,打开响应操作 # if speechstr == "记事本": # os.system('notepad') # elif speechstr == "写字板": # os.system('write') # elif speechstr == "画图板": # os.system('mspaint') # else: # pass if __name__ == '__main__': speaker.Speak("语音识别开启") wordsToAdd = ["记事本", "写字板", "画图板", ] speechReco = SpeechRecognition(wordsToAdd) while True: pythoncom.PumpWaitingMessages()
python调用语音模块时,遇见TypeError:NoneTypetakesnoarguments这种错误类型该如何解决
报错的原因是:不能调用语音开发包
解决方法:(如果你已经安装了pyWin32,它也安装了PythonWin)
1.在python35目录中找到pythonwin文件夹下的pythonwin.exe
2.双击Pythonwin运行,然后选择工具tools/commakepyutility
3.然后选择MicrosoftSpeechObjectLibrary5.4,点击OK键。
推荐一个不错的语音识别文档:https://blog.csdn.net/j2IaYU7Y/article/details/79878310
科大讯飞语音识别
参考链接:
https://blog.csdn.net/Smile_coderrr/article/details/81636015
https://blog.csdn.net/zzZ_CMing/article/details/81738317
https://blog.csdn.net/zzZ_CMing/article/details/81739193
语音识别
语音识别源于 20 世纪 50 年代早期在贝尔实验室所做的研究。早期语音识别系统仅能识别单个讲话者以及只有约十几个单词的词汇量。现代语音识别系统已经取得了很大进步,可以识别多个讲话者,并且拥有识别多种语言的庞大词汇表。
语音识别的首要部分当然是语音。通过麦克风,语音便从物理声音被转换为电信号,然后通过模数转换器转换为数据。一旦被数字化,就可适用若干种模型,将音频转录为文本。
大多数现代语音识别系统都依赖于隐马尔可夫模型(HMM)。其工作原理为:语音信号在非常短的时间尺度上(比如 10 毫秒)可被近似为静止过程,即一个其统计特性不随时间变化的过程。
许多现代语音识别系统会在 HMM 识别之前使用神经网络,通过特征变换和降维的技术来简化语音信号。也可以使用语音活动检测器(VAD)将音频信号减少到可能仅包含语音的部分。
幸运的是,对于 Python 使用者而言,一些语音识别服务可通过 API 在线使用,且其中大部分也提供了 Python SDK。
PyPI中有一些现成的语音识别软件包。其中包括:
- apiai
- google-cloud-speech
- pocketsphinx
- SpeechRcognition
- watson-developer-cloud
- wit
一些软件包(如 wit 和 apiai )提供了一些超出基本语音识别的内置功能,如识别讲话者意图的自然语言处理功能。其他软件包,如谷歌云语音,则专注于语音向文本的转换。
其中,SpeechRecognition 就因便于使用脱颖而出。
识别语音需要输入音频,而在 SpeechRecognition 中检索音频输入是非常简单的,它无需构建访问麦克风和从头开始处理音频文件的脚本,只需几分钟即可自动完成检索并运行。
SpeechRecognition 库可满足几种主流语音 API ,因此灵活性极高。其中 Google Web Speech API 支持硬编码到 SpeechRecognition 库中的默认 API 密钥,无需注册就可使用。SpeechRecognition 以其灵活性和易用性成为编写 Python 程序的最佳选择。
其中SpeechRecognition,是google出的,专注于语音向文本的转换。
wit 和 apiai 提供了一些超出基本语音识别的内置功能,如识别讲话者意图的自然语言处理功能。
SpeechRecognition库的优势
满足几种主流语音 API ,灵活性高
Google Web Speech API 支持硬编码到 SpeechRecognition 库中的默认 API 密钥,无需注册就可使用
SpeechRecognition无需构建访问麦克风和从头开始处理音频文件的脚本, 只需几分钟即可自动完成音频输入、检索并运行。因此易用性很高。
SpeechRecognition的识别器
SpeechRecognition 的核心就是识别器类。一共有七个Recognizer API ,包含多种设置和功能来识别音频源的语音,分别是:
- recognize_bing():Microsoft Bing Speech
- recognize_google(): Google Web Speech API
- recognize_google_cloud():Google Cloud Speech - requires installation of the google-cloud-speech package
- recognize_houndify(): Houndify by SoundHound
- recognize_ibm():IBM Speech to Text
- recognize_sphinx():CMU Sphinx - requires installing PocketSphinx
- recognize_wit():Wit.ai
以上七个中只有 recognition_sphinx()可与CMU Sphinx 引擎脱机工作, 其他六个都需要连接互联网。
另外,SpeechRecognition 附带 Google Web Speech API 的默认 API 密钥,可直接使用它。其他六个 API 都需要使用 API 密钥或用户名/密码组合进行身份验证,因此本文使用了 Web Speech API。
SpeechRecognition 的使用要求
To use all of the functionality of the library, you should have:
Python 2.6, 2.7, or 3.3+ (required)
需要Python 2.6、2.7和3.3以上的版本
PyAudio 0.2.11+ (required only if you need to use microphone input, Microphone)
需要安装PyAudio 0.2.11+的版本
PocketSphinx (required only if you need to use the Sphinx recognizer, recognizer_instance.recognize_sphinx)
需要安装PocketSphinx
Google API Client Library for Python (required only if you need to use the Google Cloud Speech API, recognizer_instance.recognize_google_cloud)
需要使用Google API Client Library for Python
FLAC encoder (required only if the system is not x86-based Windows/Linux/OS X)
需要安装FLAC encoder,如果系统不是X86
SpeechRecognition 支持的文件类型
支持的文件类型有:
- WAV: 必须是 PCM/LPCM 格式
- AIFF
- AIFF-C
- FLAC: 必须是初始 FLAC 格式;OGG-FLAC 格式不可用
参考:https://blog.csdn.net/qq_40965177/article/details/86766703
SpeechRecognition的Demo调试
import speech_recognition as sr # obtain audio from the microphone r = sr.Recognizer() with sr.Microphone() as source: r.adjust_for_ambient_noise(source) # listen for 1 second to calibrate the energy threshold for ambient noise levels print('say something') # print("") #监听麦克风 audio = r.listen(source) # # recognize speech using Sphinx try: print("Sphinx thinks you said " + r.recognize_sphinx(audio,language='ZH_CN')) except sr.UnknownValueError: print("Sphinx could not understand audio") except sr.RequestError as e: print("Sphinx error; {0}".format(e))
音频文件识别
import speech_recognition as sr r = sr.Recognizer() test = sr.AudioFile('./data/output/3_1.wav') with test as source: r.adjust_for_ambient_noise(source) '''record() 命令中有一个 duration 关键字参数,可使得该命令在指定的秒数后停止记录 offset 参数为 record() 命令指定起点,其值表示在开始记录的时间。offset 和 duration 关键字参数对于分割音频文件非常有用。但使用不准确会导致转录不佳。。''' # audio = r.record(source, offset=4.7, duration=2.8) audio = r.record(source) type(audio) try: # print(r.recognize_sphinx(audio, language='zh-CN')) # print("Sphinx thinks you said " + r.recognize_sphinx(audio)) '''使用谷歌api识别''' print(r.recognize_google(audio, language='zh-CN')) except sr.UnknownValueError: print("Sphinx could not understand audio") except sr.RequestError as e: print("Sphinx error; {0}".format(e))
相关文档: