• 手把手教你python制作萝莉音智能对话语音机器人,附全部源码!速速学起来!!


    别着急,先看演示

    记得三连加关,我太惨了,都没多少人关注我,呜呜!(水印名就是我b站用户名)

    前言一定要看,很重要!!!

    为了让大家真正学会,我用分模块步骤的方式讲解,这样也能让大家不仅在娱乐的同时,还能学到知识。东西有点多,你大可不必着急复制粘贴,你只需要看看我的讲解即可,当然,如果你能按照我的步骤亲自执行每一部分代码,那样你会更加学到知识,最下面可以直接下载完整的源码文件!!!别说你搞不出来了!!

    第一步实现普通智能对话

    代码如下:

    # coding=gbk
    """
    作者:川川
    时间:2021/8/21
    """
    import requests
    print('请输入你想说的:')
    while True:
        a=input()
        url='https://api.ownthink.com/bot?appid=9ffcb5785ad9617bf4e64178ac64f7b1&spoken=%s'%a
        te=requests.get(url).json()
        data=te['data']['info']['text']
        print(data)
    

    对话效果(还是比较人工智能)

    在这里插入图片描述

    第二步文字转萝莉音

    1-到百度ai开放平台,链接为:https://ai.baidu.com/ ,点击控制台,扫码登录进去
    2-申请百度语音技术api,步骤如下:

    在这里插入图片描述


    在这里插入图片描述
    然后配置如下:
    在这里插入图片描述
    点击创建即可。
    然后到管理用用去查看:(我圈出来的后面要用)
    在这里插入图片描述
    开始撸代码:

    # coding=gbk
    """
    作者:川川
    时间:2021/8/22
    私人交流群:970353786
    """
    # pip install baidu-aip
    from aip import AipSpeech
    
    """ 你的 APPID AK SK 最好是用你的替换,不要用我的 """
    APP_ID = '24734236'
    API_KEY = 'KnmsgdYdL4v9enp2iuD5e6OS'
    SECRET_KEY = 'HGhMchOle5sbzRdFqOoHkRu5P1jZR1NM'
    
    client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
    
    result = client.synthesis('空山新雨后,天气晚来秋', 'zh', 1, {
        'vol': 5,  # 音量
        'spd': 3,  # 语速
        'pit': 9,  # 语调
        'per': 3,  # 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 playsound
    playsound('auido.mp3')
    

    为了解决这个循环问题,我在网上找到了另外的办法来补救,我再创建一个play.py文件内容如下:

    from platform import system
    from abc import ABC, abstractmethod
    
    operating_system = system()
    
    if operating_system == 'Windows':
        from ctypes import c_buffer, windll
        from random import random
        from time import sleep
        from sys import getfilesystemencoding
    elif operating_system == 'Darwin':
        from AppKit import NSSound
        from Foundation import NSURL
        from time import sleep
    elif operating_system == 'Linux':
        # pathname2url escapes non-URL-safe characters
        import os
    
        try:
            from urllib.request import pathname2url
        except ImportError:
            # python 2
            from urllib import pathname2url
        import gi
    
        gi.require_version('Gst', '1.0')
        from gi.repository import Gst
    
    
    class PlaysoundException(Exception):
        pass
    
    
    class playsoundBase(ABC):
        def __init__(self):
            pass
    
        @abstractmethod
        def play(self, sound, block):
            raise NotImplemented
    
        @abstractmethod
        def stop(self):
            raise NotImplemented
    
    
    class 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 = (
                        '
        Error ' + str(errorCode) + ' for command:
    '
                        + command.decode() + '
        ' + errorBuffer.value.decode())
                raise PlaysoundException(exceptionMessage)
            return buf.value
    
    
        def 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 getcwd
                    sound = getcwd() + '/' + sound
                sound = 'file://' + sound
            url = 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 NotImplemented
    
    
    class 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 = sound
            else:
                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.html
            bus = playbin.get_bus()
            bus.poll(Gst.MessageType.EOS, Gst.CLOCK_TIME_NONE)
            playbin.set_state(Gst.State.NULL)
    
        def stop(self):
            raise NotImplemented
    
    operating_system = 'Windows'
    if operating_system == 'Windows':
        playsound = playsoundWin
    elif operating_system == 'Darwin':
        playsound = playsoundOSX
    elif operating_system == 'Linux':
        playsound = playsoundNix
    
    del operating_system
    

    第四步综合上述代码

    # coding=gbk
    """
    作者:川川
    时间:2021/8/22
    私人交流群:970353786
    """
    from play import playsound
    from aip import AipSpeech
    import requests
    """ 你的 APPID AK SK 不要用我的 """
    APP_ID = '24734236'
    API_KEY = 'KnmsgdYdL4v9enp2iuD5e6OS'
    SECRET_KEY = 'HGhMchOle5sbzRdFqOoHkRu5P1jZR1NM'
    
    client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
    
    print('请输入你想说的:')
    
    while True:
        a=input()
        url='https://api.ownthink.com/bot?appid=9ffcb5785ad9617bf4e64178ac64f7b1&spoken=%s'%a
        te=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()  # 停止
    

    完整代码下载地址

    https://github.com/89461561511656/bot

    上述步骤仅仅是讲解,如果小白不太懂,可以只需在百度ai平台申请后,将你的id和key在我的代码中换上就可以成功运行。

  • 相关阅读:
    PL/SQL 入门
    Nginx 安装和配置
    MySql 优化方案
    类加载器(ClassLoader)
    动态代理入门
    Servlet 3.0 介绍
    反射加强(一)
    Python(1)—is和==区别
    代码题(10)— 验证二叉搜索树、二叉搜索树的最近公共祖先
    代码题(9)— 二叉树的最大、最小深度、平衡二叉树
  • 原文地址:https://www.cnblogs.com/lyck/p/15216250.html
Copyright © 2020-2023  润新知