百度AI的語音合成,語音識別


1,語音的合成,識別 

后端代碼:

from aip import AipSpeech, AipNlp
import os # 語音合成 """ 你的 APPID AK SK """ # 申請的Ai.baidu.com的ID,接口,密鑰 APP_ID = '15217709' API_KEY = 'eNiP5QUsgBh6QwpbNv8Qmsy3' SECRET_KEY = 'gwhM3wDo0Kjjd1PDIxqqW4Bfex10Y4f3' # 實例化AipSpeech,AipNlp對象 client = AipSpeech(APP_ID, API_KEY, SECRET_KEY) nlp_client = AipNlp(APP_ID, API_KEY, SECRET_KEY) # 調節發音的會澤的 # 第一個可以放要轉化吃那個語音的文字 result = client.synthesis('', 'zh', 1, { "per": 4, # 表示是男音還是女音 "spd": 8, # 表示說話的速度 "pit": 6, "vol": 5, }) # 識別正確返回語音二進制 錯誤則返回dict ,這時返回的是文件文本 if not isinstance(result, dict): with open('auido.mp3', 'wb') as f: f.write(result) # 把二進制語音寫入到文件中 # 定義一個讀取文件的函數 def get_file_content(filePath): # 把wma格式的文件轉化為.pcm格式的文件 os.system(f"ffmpeg -y -i {filePath} -acodec pcm_s16le -f s16le -ac 1 -ar 16000 {filePath}.wma.pcm") # 把轉化了的格式保存到當前目錄 with open(f"{filePath}.wma.pcm", 'rb') as fp: # 返回這個文件讀取的內容 return fp.read() # 並把這個文件返回給調用者 # get_file_content("cg.m4a") # 識別本地文件, 把本地的語音文件轉成pcm個格式的文件並把語音轉化成二進制文件 res = client.asr(get_file_content('xh.m4a'), 'pcm', 16000, { 'dev_pid': 1536, }) print(res, type(res)) # {'corpus_no': '6637053740205578210', 'err_msg': 'success.', 'err_no': 0, 'result': ['給我講個笑話'], 'sn': '757488757051545309494'}, <class 'dict'>  Q = res.get("result")[0] # 取到輸入的主要內容 print(1,Q) # 1 給我講個笑話 # 判斷是不是問的是名字,是拿Q和"你叫什么"做相似度匹配如果大於0.7,則表明用戶表達的是這個意思 if nlp_client.simnet(Q, "你叫什么?").get("score") >= 0.7: A = "我的名字叫雪雪" result = client.synthesis(A, "zh", 1, { "per": 4, "pit": 8, "spd": 4, "vol": 5, }) # 如果不存在result,就打開audio.mp3的文件 if not isinstance(result, dict): with open("audio.mp3", "wb") as f: f.write(result) os.system("audio.mp3") else: # 調用圖靈機器人 import go_tuling # 傳2個參數,一個是用戶輸入的內容,並賦值給A A = go_tuling.tl(Q, "asd") # 結果賦值給result,並讀取這個文件 result = client.synthesis(A, "zh", 1, { "per": 4, "pit": 8, "spd": 4, "vol": 5, }) if not isinstance(result, dict): with open("audio.mp3", "wb") as f: f.write(result) os.system("audio.mp3")

調用圖靈的代碼:

import requests

url = "http://openapi.tuling123.com/openapi/api/v2" data_dict = { "reqType": 0, "perception": { "inputText": { "text": "北京" }, }, "userInfo": { "apiKey": "96dfe320eec549519c5168093f93b2dc", "userId": "asd", } } def tl(text, uid): # 給字典賦值text,這個text是傳過來的用戶輸入的內容 data_dict["perception"]["inputText"]["text"] = text # 並給字典賦值是哪個用戶的要求 data_dict["userInfo"]["userInfo"] = uid # 把這個消息數據反送給圖靈 res = requests.post(url, json=data_dict) # 會得到一個響應值,去json的方法 res_json = res.json() print("res:", res, type(res)) # res: <Response [200]> <class 'requests.models.Response'> print("res_json:", res_json,type(res_json)) # res_json: {'intent': {'actionName': '', 'code': 10006, 'intentName': ''}, 'results': [{'groupType': 1, 'resultType': 'text', 'values': {'text': '豬豬與爸爸 小豬與爸爸在談話小豬說:爸爸為什么上個月有人來要錢你說沒有,這個月那個人來要錢你說又沒有?小豬爸爸:哎呀,爸爸要講信用嘛!'}}]} <class 'dict'> # 返回圖靈相應的數據 return res_json.get("results")[0]["values"]["text"]

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM