Python機器人語音對話,微信自動回復!


"""Maidservant"""

import time
import os
import pyaudio
import wave
import speech_recognition as sr
from aip import AipSpeech
import requests
import json
from playsound import playsound
from wxpy import Bot


#百度語音識別API(自己申請,然后都換成自己的)
APP_ID = 'XXXXXXX'#百度語音識別id
API_KEY = 'xxxxxxxxxx'#語音識別key
SECRET_KEY = 'xxxxxxxxxxxxxxxx'#SECRET_KEY

client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)

# 圖靈API
TURING_KEY = "xxxxxxxxxx"#圖靈Key
URL = "http://openapi.tuling123.com/openapi/api/v2"
HEADERS = {'Content-Type': 'application/json;charset=UTF-8'}

bot=Bot(cache_path=True)
# 使用SpeechRecogenition轉成錄音格式
def rec(rate=16000):
    r = sr.Recognizer()
    with sr.Microphone(sample_rate=rate) as source:
        print("Please start talking")
        audio = r.listen(source)

    with open("voices/recording.wav", "wb") as f:
        f.write(audio.get_wav_data())


# 使用百度語音轉文字技術
def listen():
    with open('voices/recording.wav', 'rb') as f:
        audio_data = f.read()

    result = client.asr(audio_data, 'wav', 16000, {
        'dev_pid': 1536,
    })

    result_text = result["result"][0]
    print("You said: " + result_text)
    return result_text


# 圖靈對話
def robot(text=""):
    data = {
        "reqType": 0,
        "perception": {
            "inputText": {
                "text": ""
            },
            "selfInfo": {
                "location": {
                    "city": "西安",
                    "street": "魚化寨街"
                }
            }
        },
        "userInfo": {
            "apiKey": TURING_KEY,
            "userId": "starky"
        }
    }

    data["perception"]["inputText"]["text"] = text
    response = requests.request("post", URL, json=data, headers=HEADERS)
    response_dict = json.loads(response.text)

    result = response_dict["results"][0]["values"]["text"]
    print("AI said: " + result)
    return result


# 使用百度文字轉語音引擎
def speak(text,filename):
    result = client.synthesis(text, 'zh', 3, {
        'spd': 4,
        'vol': 5,
        'per': 4,
    })

    with open(filename, 'wb') as f:
        f.write(result)

# 播放MP3文件
def play(filename):
    playsound(filename)

filenumber = 0
final_text = ""

while True:
    rec()
    request = listen()
    my_friend = bot.friends().search(u'XXX')[0] #微信昵稱
    my_friend.send(request)
    response = robot(request)

    audiofile = f"voices/audio0{filenumber}.mp3"
    
    speak(response,audiofile)
    play(audiofile)

    final_text = final_text + "You said: " + str(request) +"\r\n"
    final_text = final_text + "MaidServant said: " + str(response) +"\r\n"
    my_friend1=bot.friends().search(u'XXXXX')[0]#微信昵稱
    my_friend1.send(response)

    filenumber = filenumber + 1

    if request.__contains__("結束"):
        break

with open(f'HouseGirl.txt', 'wb') as txt_f:
        txt_f.write(final_text.encode('utf-8'))

 


免責聲明!

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



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