python 實現語音聊天機器人的示例代碼
前言
在不遠的將來,實現一定程度上的語音支持將成為日??萍嫉幕疽?,整合了語音識別的python程序提供了其他技術無法比擬的交互性和可訪問性。最重要的是,在python程序中實現語音識別非常簡單。整個代碼實現下來還不到150行。
原理簡介
許多現代語音識別系統會在HMM識別之前使用神經網絡,通過特征變換和降維技術來簡化語音信號,也可以使用語音活動檢測器將音頻信號減少到可能包含語音的部分。
幸運的是,對于python來講,一些語音識別的服務可通過API在線使用,且其中大部分也提供了Python SDK。
本文做的聊天機器人是基于百度語音識別和圖靈機器人二者之上共同實現的。大致的流程如下圖:

原理流程圖.PNG
這里需要用的模塊庫有 requests、time、datetime、pyaudio、wave、aipspeech 等。
話不多說,上代碼:
##@氫立方 2018.0911
import requests
import time
import pygame
from datetime import datetime
from aip import AipSpeech
from pyaudio import PyAudio,paInt16
import wave
import os
framerate=8000
NUM_SAMPLES=2000
channels=1
sampwidth=2
TIME=2
def save_wave_file(filename,data):
'''save the date to the wavfile'''
wf=wave.open(filename,'wb')
wf.setnchannels(channels)
wf.setsampwidth(sampwidth)
wf.setframerate(framerate)
wf.writeframes(b"".join(data))
wf.close()
def my_record():
pa=PyAudio()
stream=pa.open(format = paInt16,channels=1,
rate=framerate,input=True,
frames_per_buffer=NUM_SAMPLES)
my_buf=[]
count=0
while count<TIME*6:#控制錄音時間
string_audio_data = stream.read(NUM_SAMPLES)
my_buf.append(string_audio_data)
count+=1
print('.')
save_wave_file('0001.wav',my_buf)
stream.close()
##def play():
## wf=wave.open(r"D:/41125.mp3",'rb')
## p=PyAudio()
## stream=p.open(format=p.get_format_from_width(wf.getsampwidth()),channels=
## wf.getnchannels(),rate=wf.getframerate(),output=True)
## while True:
## data=wf.readframes(chunk)
## if data=="":break
## stream.write(data)
## stream.close()
## p.terminate()
##
這里大家需要改成自己的ID和KEY
APP_ID = '11****843'
API_KEY = '3Mnv***8**88******GbXa'
SECRET_KEY = '147***8*88****1227684'
aipSpeech = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
def getText(url):
text = requests.post(url).json()
return text['text']
##
##key = '6ddc57c5761a4c62a30ea840e5ae163f'
#api = 'http://www.tuling123.com/openapi/api?key=' + key +'&info ='
key = '8b005db5f57556fb96dfd98fbccfab84'
api = 'http://www.tuling123.com/openapi/api?key=' + key + '&info='
##
while True:
## info = input("我說\n")
## chunk=2014
my_record()
print("錄音完成")
def get_file_content(filePath):
with open(filePath,'rb') as fp:
return fp.read()
a = aipSpeech.asr(get_file_content('0001.wav '),'wav',8000,{})
print(a)
b = str(a['result'])
info = b
url = api + info
#print(url)
text_01 = getText(url)
print("機器人回\n",text_01)
now = datetime.now().strftime("%Y-%m-%d_%H_%M_%S")
filename_01 = now + ".mp3"
result = aipSpeech.synthesis( text_01,'zh',1,{'vol': 5,'per' : 2} )
if not isinstance(result, dict):
with open(filename_01, 'wb') as f:
f.write(result)
print("--------------------------------------")
time.sleep(1)
pygame.mixer.init()
print("語音1")
file= filename_01
track = pygame.mixer.music.load(file)
pygame.mixer.music.play()
time.sleep(15)
pygame.mixer.music.stop()
pygame.quit()
運行結果如下:
小編說的是:今天看了電視劇。機器人回復的是:看了有沒有開心點
在某種意義上來說,語境還是符合常理的。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
使用BeautifulSoup爬蟲程序獲取百度搜索結果的標題和url示例
這篇文章主要介紹了使用BeautifulSoup編寫了一段爬蟲程序獲取百度搜索結果的標題和url的示例,大家參考使用吧2014-01-01
深入了解Python中Pytest Markers的使用方法
從這篇開始,逐一解決fixture是啥,mark是啥,參數request是啥,鉤子函數是啥,parametrize參數化是啥,這些問題,本片先介紹一下mark是啥,以及如何使用2023-09-09
Python中json模塊load/loads方法實戰(zhàn)以及參數詳解
經常在Python中對JSON格式的文件進行操作,今天對這些操作做一個總結,下面這篇文章主要給大家介紹了關于Python中json模塊load/loads方法實戰(zhàn)以及參數的相關資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2022-08-08
python base64圖片互轉,解決base64字符串轉PIL圖片對象報錯:binascii.Error:
在Base64編碼中,若字符串長度不是4的倍數,需在末尾添加等號作為填充,不符合此規(guī)則會導致在轉換為圖片時出現binascii.Error:Incorrectpadding錯誤,正確的填充確保編碼后的字符串可以正確轉換成圖片,避免轉換錯誤2024-09-09

