文章目录
- 别着急,先看演示
- 前言一定要看,很重要!!!
- 第一步实现普通智能对话
- 第二步文字转萝莉音
- 第三步播放音频
- 第四步综合上述代码
- 完整代码下载地址
别着急,先看演示
记得三连加关,我太惨了,都没多少人关注我,呜呜!(水印名就是我b站用户名)
python智能对话机器人演示
个人b站暂时主要讲了qq机器人制作,感兴趣点开看看:川川菜鸟b站主页
前言一定要看,很重要!!!
为了让大家真正学会,我用分模块步骤的方式讲解,这样也能让大家不仅在娱乐的同时,还能学到知识。东西有点多,你大可不必着急复制粘贴,你只需要看看我的讲解即可,当然,如果你能按照我的步骤亲自执行每一部分代码,那样你会更加学到知识,最下面可以直接下载完整的源码文件!!!别说你搞不出来了!!
第一步实现普通智能对话
代码如下:
# coding=gbk"""作者:川川时间:2021/8/21"""import requestsprint('请输入你想说的:')while True:a=input()url='https://api.ownthink.com/bot?appid=9ffcb5785ad9617bf4e64178ac64f7b1&spoken=%s'%ate=requests.get(url).json()data=te['data']['info']['text']print(data)
对话效果(还是比较人工智能)
第二步文字转萝莉音
1-到百度ai开放平台,链接为:
https://ai.baidu.com/
,点击控制台,扫码登录进去
2-申请百度语音技术api,步骤如下:
然后配置如下:
点击创建即可。
然后到管理用用去查看:(我圈出来的后面要用)
开始撸代码:
# coding=gbk"""作者:川川时间:2021/8/21"""# pip install baidu-aipfrom aip import AipSpeech""" 你的 APPID AK SK """APP_ID = '上面说的那个APP_ID复制粘贴到这里'API_KEY = '上面说的那个API_KEY复制粘贴到这里'SECRET_KEY = '上面说的那个SECRET_KEY复制粘贴到这里'client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)result = client.synthesis('你好,川川帅哥', 'zh', 1, {'vol': 5, # 音量'spd': 3, # 语速'pit': 9, # 语调'per': 4, # 0:女 1:男 3:逍遥 4:小萝莉})# 识别正确返回语音二进制 错误则返回dict 参照下面错误码if not isinstance(result, dict):with open('auido.mp3', 'wb') as f:f.write(result)
运行后,不出意外,你会看到生成了一个mp3音频,你也可以手动点开播放以下看看。
第三步播放音频
运行就会播放该音频,这个演示可以看完整视频,但是该播放方式只能播放一次,还不能循环播放,当然这是基础部分。
# coding=gbk"""作者:川川时间:2021/8/21"""from playsound import playsoundplaysound('auido.mp3')
为了解决这个循环问题,我在网上找到了另外的办法来补救,我再创建一个play.py文件内容如下:
from platform import systemfrom abc import ABC, abstractmethodoperating_system = system()if operating_system == 'Windows':from ctypes import c_buffer, windllfrom random import randomfrom time import sleepfrom sys import getfilesystemencodingelif operating_system == 'Darwin':from AppKit import NSSoundfrom Foundation import NSURLfrom time import sleepelif operating_system == 'Linux':# pathname2url escapes non-URL-safe charactersimport ostry:from urllib.request import pathname2urlexcept ImportError:# python 2from urllib import pathname2urlimport gigi.require_version('Gst', '1.0')from gi.repository import Gstclass PlaysoundException(Exception):passclass playsoundBase(ABC):def __init__(self):pass@abstractmethoddef play(self, sound, block):raise NotImplemented@abstractmethoddef stop(self):raise NotImplementedclass playsoundWin(playsoundBase):alias = ''def winCommand(self, *command):buf = c_buffer(255)command = ' '.join(command).encode(getfilesystemencoding())errorCode = int(windll.winmm.mciSendStringA(command, buf, 254, 0))if errorCode:errorBuffer = c_buffer(255)windll.winmm.mciGetErrorStringA(errorCode, errorBuffer, 254)exceptionMessage = ('\\n Error ' + str(errorCode) + ' for command:\\n'+ command.decode() + '\\n ' + errorBuffer.value.decode())raise PlaysoundException(exceptionMessage)return buf.valuedef play(self, sound, block=True):self.alias = 'playsound_' + str(random())self.winCommand('open "' + sound + '" alias', self.alias)self.winCommand('set', self.alias, 'time format milliseconds')durationInMS = self.winCommand('status', self.alias, 'length')self.winCommand('play', self.alias, 'from 0 to', durationInMS.decode())if block:sleep(float(durationInMS) / 1000.0)def stop(self):self.winCommand('stop', self.alias)def close(self):self.winCommand('close', self.alias)class playsoundOSX(playsoundBase):def play(self, sound, block=True):if '://' not in sound:if not sound.startswith('/'):from os import getcwdsound = getcwd() + '/' + soundsound = 'file://' + soundurl = NSURL.URLWithString_(sound)nssound = NSSound.alloc().initWithContentsOfURL_byReference_(url, True)if not nssound:raise IOError('Unable to load sound named: ' + sound)nssound.play()if block:sleep(nssound.duration())def stop(self):raise NotImplementedclass playsoundNix(playsoundBase):def play(self, sound, block=True):if not block:raise NotImplementedError("block=False cannot be used on this platform yet")Gst.init(None)playbin = Gst.ElementFactory.make('playbin', 'playbin')if sound.startswith(('http://', 'https://')):playbin.props.uri = soundelse:playbin.props.uri = 'file://' + pathname2url(os.path.abspath(sound))set_result = playbin.set_state(Gst.State.PLAYING)if set_result != Gst.StateChangeReturn.ASYNC:raise PlaysoundException("playbin.set_state returned " + repr(set_result))# FIXME: use some other bus method than poll() with block=False# https://lazka.github.io/pgi-docs/#Gst-1.0/classes/Bus.htmlbus = playbin.get_bus()bus.poll(Gst.MessageType.EOS, Gst.CLOCK_TIME_NONE)playbin.set_state(Gst.State.NULL)def stop(self):raise NotImplementedoperating_system = 'Windows'if operating_system == 'Windows':playsound = playsoundWinelif operating_system == 'Darwin':playsound = playsoundOSXelif operating_system == 'Linux':playsound = playsoundNixdel operating_system
第四步综合上述代码
# coding=gbk"""作者:川川时间:2021/8/22"""from play import playsoundfrom aip import AipSpeechimport requests""" 你的 APPID AK SK """APP_ID = '上面讲过的id'API_KEY = '上面讲过API_KEY'SECRET_KEY = '上面讲过SECRET_KEY'client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)print('请输入你想说的:')while True:a=input()url='https://api.ownthink.com/bot?appid=9ffcb5785ad9617bf4e64178ac64f7b1&spoken=%s'%ate=requests.get(url).json()data=te['data']['info']['text']print(data)result = client.synthesis(data, 'zh', 1, {'vol': 8, # 音量'spd': 5, # 语速'pit': 9, # 语调'per': 4, # 0:女 1:男 3:逍遥 4:小萝莉})# 识别正确返回语音二进制 错误则返回dict 参照下面错误码if not isinstance(result, dict):with open('auido.mp3', 'wb+') as f:f.write(result)p = playsound()voice_path = r"auido.mp3"p.play(voice_path) # 播放p.close() # 停止
完整代码下载地址
上述步骤仅仅是讲解,如果小白不太懂,可以只需在百度ai平台申请后,将你的id和key在我的代码中换上就可以成功运行。
https://github.com/89461561511656/bot