python調(diào)用百度語音REST API
本文實例為大家分享了python調(diào)用百度語音REST API的具體代碼,供大家參考,具體內(nèi)容如下
(百度的rest接口的部分網(wǎng)址發(fā)生了一定的變化,相關(guān)代碼已更新)
百度通過 REST API 的方式給開發(fā)者提供一個通用的 HTTP 接口,基于該接口,開發(fā)者可以輕松的獲得語音合成與語音識別能力。SDK中只提供了PHP、C和JAVA的相關(guān)樣例,使用python也可以靈活的對端口進行調(diào)用,本文描述了簡單使用Python調(diào)用百度語音識別服務 REST API 的簡單樣例。
1、語音識別與語音合成的調(diào)用
注冊開發(fā)者帳號和創(chuàng)建應用的過程就不再贅述,百度的REST API在調(diào)用過程基本分為三步:
- 獲取token
- 向Rest接口提交數(shù)據(jù)
- 處理返回數(shù)據(jù)
具體代碼如下所示:
#!/usr/bin/python3 import urllib.request import urllib import json import base64 class BaiduRest: def __init__(self, cu_id, api_key, api_secert): # token認證的url self.token_url = "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s&client_secret=%s" # 語音合成的resturl self.getvoice_url = "http://tsn.baidu.com/text2audio?tex=%s&lan=zh&cuid=%s&ctp=1&tok=%s" # 語音識別的resturl self.upvoice_url = 'http://vop.baidu.com/server_api' self.cu_id = cu_id self.getToken(api_key, api_secert) return def getToken(self, api_key, api_secert): # 1.獲取token token_url = self.token_url % (api_key,api_secert) r_str = urllib.request.urlopen(token_url).read() token_data = json.loads(r_str) self.token_str = token_data['access_token'] pass def getVoice(self, text, filename): # 2. 向Rest接口提交數(shù)據(jù) get_url = self.getvoice_url % (urllib.parse.quote(text), self.cu_id, self.token_str) voice_data = urllib.request.urlopen(get_url).read() # 3.處理返回數(shù)據(jù) voice_fp = open(filename,'wb+') voice_fp.write(voice_data) voice_fp.close() pass def getText(self, filename): # 2. 向Rest接口提交數(shù)據(jù) data = {} # 語音的一些參數(shù) data['format'] = 'wav' data['rate'] = 8000 data['channel'] = 1 data['cuid'] = self.cu_id data['token'] = self.token_str wav_fp = open(filename,'rb') voice_data = wav_fp.read() data['len'] = len(voice_data) data['speech'] = base64.b64encode(voice_data).decode('utf-8') post_data = json.dumps(data) r_data = urllib.request.urlopen(self.upvoice_url,data=bytes(post_data,encoding="utf-8")).read() # 3.處理返回數(shù)據(jù) return json.loads(r_data)['result'] if __name__ == "__main__": # 我的api_key,供大家測試用,在實際工程中請換成自己申請的應用的key和secert api_key = "SrhYKqzl3SE1URnAEuZ0FKdT" api_secert = "hGqeCkaMPb0ELMqtRGc2VjWdmjo7T89d" # 初始化 bdr = BaiduRest("test_python", api_key, api_secert) # 將字符串語音合成并保存為out.mp3 bdr.getVoice("你好北京郵電大學!", "out.mp3") # 識別test.wav語音內(nèi)容并顯示 print(bdr.getText("out.wav"))
2、調(diào)用pyaudio使用麥克風錄制聲音
python中的pyaudio庫可以直接通過麥克風錄制聲音,可使用pip進行安裝。我們可以通過調(diào)用該庫,獲取到wav測試語音。
具體代碼如下所示:
#!/usr/bin/python3 # -*- coding: utf-8 -*- from pyaudio import PyAudio, paInt16 import numpy as np from datetime import datetime import wave class recoder: NUM_SAMPLES = 2000 #pyaudio內(nèi)置緩沖大小 SAMPLING_RATE = 8000 #取樣頻率 LEVEL = 500 #聲音保存的閾值 COUNT_NUM = 20 #NUM_SAMPLES個取樣之內(nèi)出現(xiàn)COUNT_NUM個大于LEVEL的取樣則記錄聲音 SAVE_LENGTH = 8 #聲音記錄的最小長度:SAVE_LENGTH * NUM_SAMPLES 個取樣 TIME_COUNT = 60 #錄音時間,單位s Voice_String = [] def savewav(self,filename): wf = wave.open(filename, 'wb') wf.setnchannels(1) wf.setsampwidth(2) wf.setframerate(self.SAMPLING_RATE) wf.writeframes(np.array(self.Voice_String).tostring()) # wf.writeframes(self.Voice_String.decode()) wf.close() def recoder(self): pa = PyAudio() stream = pa.open(format=paInt16, channels=1, rate=self.SAMPLING_RATE, input=True, frames_per_buffer=self.NUM_SAMPLES) save_count = 0 save_buffer = [] time_count = self.TIME_COUNT while True: time_count -= 1 # print time_count # 讀入NUM_SAMPLES個取樣 string_audio_data = stream.read(self.NUM_SAMPLES) # 將讀入的數(shù)據(jù)轉(zhuǎn)換為數(shù)組 audio_data = np.fromstring(string_audio_data, dtype=np.short) # 計算大于LEVEL的取樣的個數(shù) large_sample_count = np.sum( audio_data > self.LEVEL ) print(np.max(audio_data)) # 如果個數(shù)大于COUNT_NUM,則至少保存SAVE_LENGTH個塊 if large_sample_count > self.COUNT_NUM: save_count = self.SAVE_LENGTH else: save_count -= 1 if save_count < 0: save_count = 0 if save_count > 0 : # 將要保存的數(shù)據(jù)存放到save_buffer中 #print save_count > 0 and time_count >0 save_buffer.append( string_audio_data ) else: #print save_buffer # 將save_buffer中的數(shù)據(jù)寫入WAV文件,WAV文件的文件名是保存的時刻 #print "debug" if len(save_buffer) > 0 : self.Voice_String = save_buffer save_buffer = [] print("Recode a piece of voice successfully!") return True if time_count==0: if len(save_buffer)>0: self.Voice_String = save_buffer save_buffer = [] print("Recode a piece of voice successfully!") return True else: return False if __name__ == "__main__": r = recoder() r.recoder() r.savewav("test.wav")
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
- python使用ctypes庫調(diào)用DLL動態(tài)鏈接庫
- Python調(diào)用REST API接口的幾種方式匯總
- 如何使用python的ctypes調(diào)用醫(yī)保中心的dll動態(tài)庫下載醫(yī)保中心的賬單
- python使用ctypes調(diào)用擴展模塊的實例方法
- python中使用ctypes調(diào)用so傳參設(shè)置遇到的問題及解決方法
- Python使用ctypes調(diào)用C/C++的方法
- python調(diào)用百度REST API實現(xiàn)語音識別
- Python調(diào)用C語言的方法【基于ctypes模塊】
- Python如何通過subprocess調(diào)用adb命令詳解
- Python 調(diào)用 ES、Solr、Phoenix的示例代碼
相關(guān)文章
python數(shù)據(jù)挖掘Apriori算法實現(xiàn)關(guān)聯(lián)分析
這篇文章主要為大家介紹了python數(shù)據(jù)挖掘Apriori算法實現(xiàn)關(guān)聯(lián)分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-05-05深入理解python中實例方法的第一個參數(shù)self
在Python中,self?是類的實例方法的一個參數(shù),代表類的實例對象本身,在本篇文章中,我們將深入探討?self?的工作原理以及它在Python編程中的重要性,需要的可以參考下2023-09-09以tensorflow庫為例講解Pycharm中如何更新第三方庫
這篇文章主要介紹了以tensorflow庫為例講解Pycharm中如何更新第三方庫,文章介紹有詳細流程,需要的小伙伴可以參考一下,希望對你的學習工作有所幫助2022-03-03Python實現(xiàn)對特定列表進行從小到大排序操作示例
這篇文章主要介紹了Python實現(xiàn)對特定列表進行從小到大排序操作,涉及Python文件讀取、計算、正則匹配、排序等相關(guān)操作技巧,需要的朋友可以參考下2019-02-02Python?Anaconda以及Pip配置清華鏡像源代碼示例
Anaconda指的是一個開源的Python發(fā)行版本,其包含了conda、Python等180多個科學包及其依賴項,下面這篇文章主要給大家介紹了關(guān)于Python?Anaconda以及Pip配置清華鏡像源的相關(guān)資料,需要的朋友可以參考下2024-03-03Postman安裝與使用詳細教程 附postman離線安裝包
這篇文章主要介紹了Postman安裝與使用詳細教程 附postman離線安裝包,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-03-03