强调:不用登录注册,直接使用就好
青云客智能聊天机器人API
python代码,直接可以运行:
1、安装库:
pip install requests pyttsx3 SpeechRecognition sounddevice numpy scipy
2、完整代码:
import requests
import pyttsx3
import speech_recognition as sr
import sounddevice as sd
import numpy as np
import scipy.io.wavfile as wavfile
import tempfileclass ChatBot:def __init__(self, api_url, key="free", appid="0"):self.api_url = api_urlself.key = keyself.appid = appidself.tts_engine = pyttsx3.init()self.tts_engine.setProperty('rate', 150) # 设置语速self.tts_engine.setProperty('volume', 1.0) # 设置音量 (0.0到1.0)def send_message(self, message):params = {"key": self.key,"appid": self.appid,"msg": message}try:response = requests.get(self.api_url, params=params)response.raise_for_status() # 检查请求是否成功data = response.json()if data.get("result") == 0:return data.get("content")else:return "对不起,我无法处理您的请求。"except requests.RequestException as e:return f"请求失败:{e}"def speak(self, text):self.tts_engine.say(text)self.tts_engine.runAndWait()def recognize_speech():# 设置录音参数sample_rate = 16000 # 采样率duration = 5 # 录音时长,秒print("请开始说话...")try:# 录制音频audio_data = sd.rec(int(sample_rate * duration), samplerate=sample_rate, channels=1, dtype='int16')sd.wait() # 等待录音完成# 保存临时音频文件with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as temp_audio:wavfile.write(temp_audio.name, sample_rate, audio_data)temp_audio_path = temp_audio.name# 使用 speech_recognition 进行语音识别recognizer = sr.Recognizer()with sr.AudioFile(temp_audio_path) as source:audio = recognizer.record(source)text = recognizer.recognize_google(audio, language="zh-CN")print(f"你: {text}")return textexcept sr.UnknownValueError:print("无法识别语音,请再试一次。")return Noneexcept sr.RequestError as e:print(f"语音识别服务出错: {e}")return Noneexcept Exception as e:print(f"录音出错: {e}")return Nonedef main():bot = ChatBot(api_url="http://api.qingyunke.com/api.php")print("欢迎使用语音聊天机器人!说“退出”结束对话。")bot.speak("欢迎使用语音聊天机器人,说退出结束对话。")while True:user_input = recognize_speech()if user_input is None:continueif "退出" in user_input:print("机器人: 再见!")bot.speak("再见!")breakresponse = bot.send_message(user_input)print(f"机器人: {response}")bot.speak(response)if __name__ == "__main__":main()
成功的同学,麻烦关注支持一下哦~~