java实现小艾机器人陪聊

各位大佬,好久没有写新的东西给大家了,现在给大家来一个陪聊解闷的小艾机器人,来陪伴大家,希望大家喜欢哦!^- ^
现在可多手机上都有只能语音机器人,虽然说的话有些牛头不对马嘴的,但是在哪那么某一个时候,还是能逗你一下的,现在,博主页为大家送上一个机器人,闲话不多说,上干活
第一电路,环境依赖
其实,小艾机器人也是属于人工智能方面的,其添加的依赖也不是一般常用的依赖,当然,如果有腻害的大佬有更好的推荐依赖,欢迎评论留言
本次使用的是青课云的小艾机器人,只需要调用他的api就可以进行使用大的对话功能了,相关的依赖如下
核心依赖地址:http://api.qingyunke.com/api.php?key=free&appid=0&msg=%s
这个地址是调用后返回机器人语句的,除去这个关键的核心,也就没有其他的了,比较,只是和机器人聊天罢了
相关代码如下

    /**
     * 获取机器人响应回答结果
     *
     * @param msg 请求问题
     * @return 机器人响应结果
     */
    @Override
    public ResponseVO getReplyMsg(String msg) {
        String api = null;
        try {
            api = String.format(apiTpl, URLEncoder.encode(msg, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String result = HttpUtils.request(api);
        if (StringUtils.isEmpty(result)) {
            result = "我没有听懂你说的是什么东东!";
        }
        return gson.fromJson(result, ResponseVO.class);
    }

这里就是调用的关键方法了,而其中的apiTpL就是上面提到的那个URL了,对于httpUtil我也附上给大家,方便大家实现案例

package com.hui.demo.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @program: hui_product_demo
 * @ClassName HttpUtils
 * @description: 调用青课云接口工具类
 * @author: liuHui
 * @create: 2021-11-29 16:23
 * @Version 1.0
 **/
public class HttpUtils {

    public static String request(String api) {

        HttpURLConnection connection = null;
        int responseCode = 0;
        try {
            URL url = new URL(api);
            //获取对应的连接对象
            connection = (HttpURLConnection) url.openConnection();
            responseCode = connection.getResponseCode();
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (200 <= responseCode && responseCode <= 299) {
            try (InputStream inputStream = connection.getInputStream();
                 BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
            ) {
                StringBuilder response = new StringBuilder();
                String currentLine;
                while ((currentLine = in.readLine()) != null) {
                    response.append(currentLine);
                }
                String result = response.toString();
                return result;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;

    }
}

这就是获取到机器人的对话消息了,是不是很简单!
你是不是以为到这,这边博客就已经结束了,当然不是呀,这才获取到对话,怎么让机器人把对话读出来呢,不读出来,哪还有什么好玩的,对不对!这就上,前方高能哦!

需要读取文字内容转换成语音的,需要用到一个名为jacob的maven依赖,但是这个依赖在maven仓库暂没有提供下载,也就是说,这个需要大家通过其他途径去获取了,等依赖下载下来完成后,我们就可以使用Jacob的相关功能了
附上核心处理代码

public static void showText(){
        ActiveXComponent sap = new ActiveXComponent("Sapi.SpVoice");
        // 音量 0-100
        sap.setProperty("Volume", new Variant(100));
        // 语音朗读速度 -10 到 +10
        sap.setProperty("Rate", new Variant(0));
        // 获取执行对象
        Dispatch sapo = sap.getObject();
        // 执行朗读
        Dispatch.call(sapo, "Speak", new Variant("尊敬的大佬,请给我取个响亮的名字!"));
        Scanner scanner = new Scanner(System.in);
        String name = scanner.nextLine();
        Dispatch.call(sapo, "Speak", new Variant("尊敬的大佬,"+name+"这个名字可真好听!"));
        Dispatch.call(sapo, "Speak", new Variant("现在让我们愉快的聊天吧!"));
        while (true) {
            String input = scanner.nextLine();
            if ("88".equalsIgnoreCase(input)) {
                Dispatch.call(sapo, "Speak", new Variant("欢迎下次使用,拜拜!"));
                break;
            } else {
                ResponseVO response = robotService.getReplyMsg(input);
                if (response != null && response.getCode() == 0) {
                    try {
                        Dispatch.call(sapo, "Speak", new Variant(new String(response.getContent().getBytes(), "UTF-8")));
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                } else {
                    Dispatch.call(sapo, "Speak", new Variant("大佬你刚刚这句话我没听懂,可否再陈述一次!"));
                }
            }

        }
        scanner.close();
        // 关闭执行对象
        sapo.safeRelease();

    }

这上面写的是一个案例,通过控制台输入与机器人进行交流,并将机器人返回的消息转换成语音告诉你他的回答,到这,小艾同学机器嗯算是OK了

但是博主呢是一个力求完美的人,手机上不是语音对话吗,而咱们刚实现的代码是需要打字文字交流的呀,多费劲,其实博主也去找了相关的知识,需要付费的,都是,比如腾讯云用的语音转换工具,在某荣耀和某新上用的都是这个转换工具,大家如果有需求的话可以去腾讯云中下载SDK然后注册上自己的项目,进行使用,使用的过程大家另行百度了。

然后,为了完善我们这个文字交流的,博主也想了一下方法,就是用java自带的窗口来优化使用呀,对不对,虽然也是打字,但是最起码有了一个用户输入的地方,可以打成EXE文件进行使用,方便用户操作了,下面也附上代码,供大家实现基础案例

package com.hui.demo.business.controller;

import com.hui.demo.business.service.RobotService;
import com.hui.demo.business.service.RobotServiceImpl;
import com.hui.demo.model.bo.ProductConfig;
import com.hui.demo.model.vo.ResponseVO;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import org.springframework.util.StringUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.ImageObserver;
import java.awt.image.ImageProducer;
import java.io.UnsupportedEncodingException;
import java.util.Scanner;

/**
 * @program: hui_product_demo
 * @ClassName JframeWindow
 * @description: 窗口输入
 * @author: liuHui
 * @create: 2021-11-30 11:20
 * @Version 1.0
 **/
public class JframeWindow {

    private static String msg = "";
    private static String newMsg = "";
    private static final RobotService robotService = new RobotServiceImpl(new ProductConfig());


    public static void main(String[] args) {
        inputWindows();
    }

    /**
     * 创建一个弹出窗中可以输入的窗口
     */
    public static void inputWindows() {
        showMe();
        JFrame jf = new JFrame("小艾聊天室");
        jf.setSize(600, 600);
        jf.setLocation(150, 150);
        jf.setLayout(new FlowLayout(FlowLayout.CENTER, 30, 30));
        JTextField textField = new JTextField(30);
        textField.setSize(300,50);
        ImageIcon background = new ImageIcon("D:\\hui_product_demo\\src\\main\\resources\\image\\01.jpg");// 背景图片
        JLabel labelImage = new JLabel(background);// 把背景图片显示在一个标签里面
        // 把标签的大小位置设置为图片刚好填充整个面板
        labelImage.setBounds(0, 0, background.getIconWidth(),
                background.getIconHeight());
        // 把内容窗格转化为JPanel,否则不能用方法setOpaque()来使内容窗格透明
        JPanel jp =(JPanel) jf.getContentPane();
        jp.setOpaque(false);
        // 内容窗格默认的布局管理器为BorderLayout
        jp.setLayout(new FlowLayout());
        JButton jButton = new JButton("提交");
        JLabel title = new JLabel("请输入");
        title.setSize(300,50);
        jButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String inputText = textField.getText().trim();
                if (("").equals(inputText)) {
                    JOptionPane.showMessageDialog(null, "请输入您的聊天内容:");
                    return;
                }
                if (!StringUtils.isEmpty(inputText)) {
                    msg = inputText;
                    if (StringUtils.isEmpty(newMsg)) {
                        newMsg = inputText;
                        msg = "";
                    } else {
                        msg = inputText;
                        newMsg = "";
                    }
                    showText();
                    textField.setText("");
                    return;
                }
            }
        });
//         加入顺序影响着在页面上的展示位置
        jf.add(title);
        jf.add(textField);
        jf.add(jButton);
        jf.setLocationRelativeTo(null);
        jf.setVisible(true);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


        jf.getLayeredPane().setLayout(null);
        // 把背景图片添加到分层窗格的最底层作为背景
        jf.getLayeredPane().add(labelImage, new Integer(Integer.MIN_VALUE));
        jf.setResizable(false);
        jf.setVisible(true);
    }


    public static void showMe() {
        ActiveXComponent sap = new ActiveXComponent("Sapi.SpVoice");
        // 音量 0-100
        sap.setProperty("Volume", new Variant(100));
        // 语音朗读速度 -10 到 +10
        sap.setProperty("Rate", new Variant(0));
        // 获取执行对象
        Dispatch sapo = sap.getObject();
        // 执行朗读
        Dispatch.call(sapo, "Speak", new Variant("尊敬的大佬,你好!现在让我们愉快的聊天吧!"));
        sapo.safeRelease();
    }
    public static void showText() {
        ActiveXComponent sap = new ActiveXComponent("Sapi.SpVoice");
        // 音量 0-100
        sap.setProperty("Volume", new Variant(100));
        // 语音朗读速度 -10 到 +10
        sap.setProperty("Rate", new Variant(0));
        // 获取执行对象
        Dispatch sapo = sap.getObject();
        String input = "";
        if (newMsg.equals("")) {
            input = msg;
        } else {
            input = newMsg;
        }
        if ("88".equalsIgnoreCase(input)) {
            Dispatch.call(sapo, "Speak", new Variant("欢迎下次使用,拜拜!"));
        } else {
            ResponseVO response = robotService.getReplyMsg(input);
            if (response != null && response.getCode() == 0) {
                try {
                    Dispatch.call(sapo, "Speak", new Variant(new String(response.getContent().getBytes(), "UTF-8")));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            } else {
                Dispatch.call(sapo, "Speak", new Variant("大佬你刚刚这句话我没听懂,可否再陈述一次!"));
            }
        }
        sapo.safeRelease();

    }





}

上面的代码是博主刚刚写好的,并且设置了一下背景图片,大家可以看看,代码不难,就不做过多的说明了,希望需要对需要用到的同学有所帮助哦,如果你给我点个赞的话,我就把maven依赖也给你送上,其他博主可都是收钱的呢?

白捡的jar包maven依赖来了(不要告诉其他的博主,不然我怕挨揍 ^ - ^ )
链接: https://pan.baidu.com/s/1yc60JEY0Rk1Ja-5Ev3on0A
提取码: qan7
使用方法也在下载下来的里面有了,记得点赞关注哦!

  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值