前言:
簡單描述一下自己的實現思路:
1.運行程序 ---> 2.語音輸入 ---> 3.語音轉文字 ---> 4.聊天回復 ---> 5.文字轉語音 ---> 6.播放語音
這里的語音功能全部使用的是百度語音的API,聊天回復這里使用的是圖靈機器人,Python版本使用的是Python3.6。由於我筆記本的錄音效果較差,我就用了在家吃土的藍牙音響,作為語音的輸入輸出設備,有點智能音響的感覺了。
准備:
百度智能雲登錄\注冊鏈接:https://cloud.baidu.com/,這里進入百度語音的管理界面,創建一個新應用后,將該應用的AppID、API Key以及Secret Key記錄下來,后面的Python腳本中需要用到。
圖靈機器人登錄\注冊鏈接:http://www.tuling123.com/sso-web/login
這里選擇創建機器人,根據引導,配置完成后,進入管理界面,記錄下該機器人的Key。
代碼:
以下代碼中,需要自己填寫自己申請的百度語音的key以及圖靈機器人的Key
1 import time 2 import os 3 import pygame 4 import urllib.request 5 import json 6 from aip import AipSpeech 7 import speech_recognition as sr 8 import urllib3 9 10 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) # 忽略百度api連接時的報錯信息。 11 12 # Baidu Speech API 13 APP_ID = '這里填自己的ID' 14 API_KEY = '這里填自己的APIKey' 15 SECRET_KEY = '這里填自己的KEY' 16 17 client = AipSpeech(APP_ID,API_KEY,SECRET_KEY) 18 19 #Turing API 20 TURING_KEY = "這里填自己的圖靈機器人API" 21 API_URL = "http://openapi.tuling123.com/openapi/api/v2" 22 23 # 錄音 24 def rec(rate=16000): 25 r = sr.Recognizer() 26 with sr.Microphone(sample_rate=rate) as source: 27 print("please say something") 28 audio = r.listen(source) 29 30 with open("recording.wav", "wb") as f: 31 f.write(audio.get_wav_data()) 32 33 # 百度語音轉文字 34 def listen(): 35 with open('recording.wav', 'rb') as f: 36 audio_data = f.read() 37 38 result = client.asr(audio_data, 'wav', 16000, { 39 'dev_pid': 1536, 40 }) 41 42 text_input = result["result"][0] 43 44 print("我說: " + text_input) 45 Robot_think(text_input) 46 47 48 # 圖靈處理 49 def Robot_think(text_input): 50 req = { 51 "perception": 52 { 53 "inputText": 54 { 55 "text": text_input 56 }, 57 58 "selfInfo": 59 { 60 "location": 61 { 62 "city": "東營", 63 "province": "東營", 64 "street": "黃河路" 65 } 66 } 67 }, 68 "userInfo": 69 { 70 "apiKey": TURING_KEY, 71 "userId": "這里隨便填" 72 } 73 } 74 # print(req) 75 # 將字典格式的req編碼為utf8 76 req = json.dumps(req).encode('utf8') 77 # print(req) 78 79 http_post = urllib.request.Request(API_URL, data=req, headers={'content-type': 'application/json'}) 80 response = urllib.request.urlopen(http_post) 81 response_str = response.read().decode('utf8') 82 # print(response_str) 83 response_dic = json.loads(response_str) 84 # print(response_dic) 85 86 intent_code = response_dic['intent']['code'] 87 results_text = response_dic['results'][0]['values']['text'] 88 print("AI說: " + results_text) 89 du_say(results_text) 90 play_mp3('robot.mp3') 91 # 文字轉語音 92 def du_say(results_text): 93 # per 3是漢子 4是妹子,spd 是語速,vol 是音量 94 result = client.synthesis(results_text, 'zh', 1, { 95 'vol': 5, 'per': 4, 'spd': 4 96 }) 97 # 識別正確返回語音二進制 錯誤則返回dict 參照下面錯誤碼 98 if not isinstance(result, dict): 99 with open('robot.mp3', 'wb') as f: 100 f.write(result) 101 102 # 播放Mp3文件 103 def play_mp3(file): 104 pygame.mixer.init() 105 pygame.mixer.music.load(file) 106 pygame.mixer.music.play() 107 while pygame.mixer.music.get_busy(): 108 time.sleep(1) 109 pygame.mixer.music.stop() 110 pygame.mixer.quit() 111 112 if __name__ == '__main__': 113 while True: 114 rec() 115 listen()
總結:
這里只是簡單的實現了自己提出的功能,還有可以完善的地方,比如語音喚醒,還有語音輸入是空白的時候,自動處理,而不是程序異常結束。