基于python實(shí)現(xiàn)百度語音識別和圖靈對話
更新時(shí)間:2020年11月02日 15:38:14 作者:小蝸牛嘰咕往前
這篇文章主要介紹了基于python實(shí)現(xiàn)百度語音識別和圖靈對話,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
圖例如下

https://github.com/Dongvdong/python_Smartvoice
- 上電后,只要周圍聲音超過 2000,開始錄音5S
- 錄音上傳百度識別,并返回結(jié)果文字輸出
- 繼續(xù)等待,周圍聲音是否超過2000,沒有就等待。
- 點(diǎn)用電腦API語音交互
代碼如下
# -*- coding: utf-8 -*-
# 樹莓派
from pyaudio import PyAudio, paInt16
import numpy as np
from datetime import datetime
import wave
import time
import requests#導(dǎo)入requests庫
import urllib, urllib.request, pycurl
import base64
import json
import os
import sys
from imp import reload
# 調(diào)用電腦API生成語音交互
import speech
import win32api
import os
import sys
import time
import win32con
reload(sys)
#sys.setdefaultencoding( "utf-8" )
#一些全局變量
save_count = 0
save_buffer = []
t = 0
sum = 0
time_flag = 0
flag_num = 0
filename = ''
duihua = '1'
def getHtml(url):
html= requests.get(url)
# html.encoding = 'utf-8'#防止中文亂碼
return html.text
def get_token():
apiKey = "AxXDYEN27Ks9XHocsGmCEdPm"
secretKey = "61cd52759f4d704d91c155a22ff7183d"
auth_url = "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=" + apiKey + "&client_secret=" + secretKey;
res = requests.get(auth_url)
#res.encoding = 'utf-8'#防止中文亂碼
#print (res.text)
return json.loads(res.text)['access_token']
def dump_res(buf):#輸出百度語音識別的結(jié)果
global duihua
#print ("字符串類型")
#print (buf)
a = eval(buf)
#print (type(a))
if a['err_msg']=='success.':
#print (a['result'][0])#終于搞定了,在這里可以輸出,返回的語句
duihua = a['result'][0]
print ("我:"+duihua)
def use_cloud(token):#進(jìn)行合成
fp = wave.open(filename, 'rb')
nf = fp.getnframes()
f_len = nf * 2
audio_data = fp.readframes(nf)
cuid = "9120612" #產(chǎn)品id
srv_url = 'http://vop.baidu.com/server_api' + '?cuid=' + cuid + '&token=' + token
http_header = [
'Content-Type: audio/pcm; rate=8000',
'Content-Length: %d' % f_len
]
c = pycurl.Curl()
c.setopt(pycurl.URL, str(srv_url)) #curl doesn't support unicode
#c.setopt(c.RETURNTRANSFER, 1)
c.setopt(c.HTTPHEADER, http_header) #must be list, not dict
c.setopt(c.POST, 1)
c.setopt(c.CONNECTTIMEOUT, 30)
c.setopt(c.TIMEOUT, 30)
c.setopt(c.WRITEFUNCTION, dump_res)
c.setopt(c.POSTFIELDS, audio_data)
c.setopt(c.POSTFIELDSIZE, f_len)
c.perform() #pycurl.perform() has no return val
# 將data中的數(shù)據(jù)保存到名為filename的WAV文件中
def save_wave_file(filename, data):
wf = wave.open(filename, 'wb')
wf.setnchannels(1)
wf.setsampwidth(2)
wf.setframerate(SAMPLING_RATE)
wf.writeframes(b"".join(data))
wf.close()
NUM_SAMPLES = 2000 # pyAudio內(nèi)部緩存的塊的大小
SAMPLING_RATE = 8000 # 取樣頻率
LEVEL = 1500 # 聲音保存的閾值
COUNT_NUM = 20 # NUM_SAMPLES個(gè)取樣之內(nèi)出現(xiàn)COUNT_NUM個(gè)大于LEVEL的取樣則記錄聲音
SAVE_LENGTH = 8 # 聲音記錄的最小長度:SAVE_LENGTH * NUM_SAMPLES 個(gè)取樣
exception_on_overflow=False
# 開啟聲音輸入pyaudio對象
pa = PyAudio()
stream = pa.open(format=paInt16, channels=1, rate=SAMPLING_RATE, input=True,
frames_per_buffer=NUM_SAMPLES)
token = get_token()#獲?。簦铮耄澹?
key = '35ff2856b55e4a7f9eeb86e3437e23fe'
api = 'http://www.tuling123.com/openapi/api?key=' + key + '&info='
while(True):
# 讀入NUM_SAMPLES個(gè)取樣
string_audio_data = stream.read(NUM_SAMPLES,False);
# 將讀入的數(shù)據(jù)轉(zhuǎn)換為數(shù)組
audio_data = np.fromstring(string_audio_data, dtype=np.short)
# 計(jì)算大于LEVEL的取樣的個(gè)數(shù)
large_sample_count = np.sum( audio_data > LEVEL )
temp = np.max(audio_data)
if temp > 2000 and t == 0:
t = 1#開啟錄音
print ("---------主人我在聽你說?。?S)----------")
begin = time.time()
# print (temp)
if t:
#print (np.max(audio_data))
if np.max(audio_data)<1000:
sum += 1
# print (sum)
end = time.time()
if end-begin>5:
time_flag = 1
# print ("五秒到了,準(zhǔn)備結(jié)束")
# 如果個(gè)數(shù)大于COUNT_NUM,則至少保存SAVE_LENGTH個(gè)塊
if large_sample_count > COUNT_NUM:
save_count = SAVE_LENGTH
else:
save_count -= 1
if save_count < 0:
save_count = 0
if save_count > 0:
# 將要保存的數(shù)據(jù)存放到save_buffer中
save_buffer.append(string_audio_data )
else:
# 將save_buffer中的數(shù)據(jù)寫入WAV文件,WAV文件的文件名是保存的時(shí)刻
#if time_flag:
if len(save_buffer) > 0 or time_flag:
#filename = datetime.now().strftime("%Y-%m-%d_%H_%M_%S") + ".wav"#原本是用時(shí)間做名字
filename = str(flag_num)+".wav"
flag_num += 1
save_wave_file(filename, save_buffer)
save_buffer = []
t = 0
sum =0
time_flag = 0
# print (filename, "保存成功正在進(jìn)行語音識別")
use_cloud(token)
# print (duihua)
info = duihua
duihua = ""
request = api + str(info)
response = getHtml(request)
# print ( "-----1-----")
dic_json = json.loads(response)
a = dic_json['text']
unicodestring = a
# 將Unicode轉(zhuǎn)化為普通Python字符串:"encode"
utf8string = unicodestring.encode("utf-8")
print ("科塔娜:"+str(a))
# 電腦說話
speech.say(str(a))
url = "http://tsn.baidu.com/text2audio?tex="+dic_json['text']+"&lan=zh&per=0&pit=1&spd=7&cuid=7519663&ctp=1&tok=25.41bf315625c68b3e947c49b90788532d.315360000.1798261651.282335-9120612"
os.system('mpg123 "%s"'%(url))
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:
- python語音識別的轉(zhuǎn)換方法
- Python結(jié)合百度語音識別實(shí)現(xiàn)實(shí)時(shí)翻譯軟件的實(shí)現(xiàn)
- python錄音并調(diào)用百度語音識別接口的示例
- python3實(shí)現(xiàn)語音轉(zhuǎn)文字(語音識別)和文字轉(zhuǎn)語音(語音合成)
- python語音識別指南終極版(有這一篇足矣)
- python之語音識別speech模塊
- 使用Python和百度語音識別生成視頻字幕的實(shí)現(xiàn)
- Python實(shí)現(xiàn)語音識別和語音合成功能
- python版百度語音識別功能
- Python迅速掌握語音識別之知識儲(chǔ)備篇
相關(guān)文章
解決django model修改添加字段報(bào)錯(cuò)的問題
今天小編就為大家分享一篇解決django model修改添加字段報(bào)錯(cuò)的問題,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11
在Python中字典按值排序的實(shí)現(xiàn)方法
這篇文章主要介紹了在Python中字典按值排序的實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11
Python可執(zhí)行文件反編譯教程(exe轉(zhuǎn)py)
python的便利性,使得如今許多軟件開發(fā)者、黑客都開始使用python打包成exe的方式進(jìn)行程序的發(fā)布,那么Python如何反編譯可執(zhí)行文件,本文就來介紹一下,感興趣的可以了解一下2021-12-12
Python設(shè)計(jì)模式中的結(jié)構(gòu)型適配器模式
這篇文章主要介紹了Python設(shè)計(jì)中的結(jié)構(gòu)型適配器模式,適配器模式即Adapter?Pattern,將一個(gè)類的接口轉(zhuǎn)換成為客戶希望的另外一個(gè)接口,下文內(nèi)容具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-02-02
python如何將兩個(gè)數(shù)據(jù)表中的對應(yīng)數(shù)據(jù)相加
這篇文章主要介紹了python如何將兩個(gè)數(shù)據(jù)表中的對應(yīng)數(shù)據(jù)相加問題,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-08-08

