使用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))
相關文檔: