Java 监控 7*24小时全球实时财经新闻直播- 语音播报

引入jacob

<!-- https://mvnrepository.com/artifact/com.jacob/jacob 文字转语音 -->
<dependency>
  <groupId>com.hynnet</groupId>
  <artifactId>jacob</artifactId>
  <version>1.18</version>
</dependency>

 下载DLL 语音库 

 地址:https://files.cnblogs.com/files/w1441639547/jacob-1.18-x64.rar

把jacob-1.18-x64.dll文件复制到jdk安装位置的bin目录下

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import sun.audio.AudioPlayer;

import java.awt.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;


public class XinLang {


    static String url = "http://zhibo.sina.com.cn/api/zhibo/feed?\\%20callback=jQuery0&page=1&page_size=1&zhibo_id=152\\%20&tag_id=0&dire=f&dpc=1&pagesize=1&_=0%20Request%20Method:GET";
    static final String path = XinLang.class.getResource("/").getPath();

    public static void main(String[] args) {

        List<DataInfo> infoList = null;
        while (true){
            try {
                Thread.sleep(1000);
                List<DataInfo> dataInfos = resultData(url);
                if(infoList != null && infoList.get(0).getText().equals(dataInfos.get(0).getText())){
                    continue;
                }
                infoList = dataInfos ;
                System.out.println("=========================================================");
                for(DataInfo dataInfo :dataInfos){
                    System.out.print("["+dataInfo.getTag() + "]");
                    System.out.println(dataInfo.getText());
                    System.out.println(dataInfo.getCrateTime());
                    //System.out.println(dataInfo.getUrl());
                    textToSpeech(dataInfo.getText());
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }


//        String str = "【深高速:拟受让深圳控股湾区发展71.83%权益】深高速公告,为了积极推动国有企业改革,完善国有资产产业布局,公司间接控股股深投控拟将其拥有的深圳控股湾区发展全部71.83%权益转让予公司。";
//        textToSpeech(str);
    }


    /**
     *  如果jacob-1.18-x64.dll 放在 jdk目录下的bin文件夹,static 可以注释 
     *  static 里的代码是初始化 DLL库的
     */
    static {
        String dll =  path + "jacob-1.18-x64.dll";
        try {
            String libpath = System.getProperty("java.library.path");
            if (libpath == null || libpath.length() == 0) {
                throw new RuntimeException("java.library.path is null");
            }
            //javaBinPath   jdk的bin目录D:\Program Files\Java\jdk1.6.0_11\bin
            String javaBinPath = null;
            StringTokenizer st = new StringTokenizer(libpath,
                    System.getProperty("path.separator"));
            if (st.hasMoreElements()) {
                javaBinPath = st.nextToken();
            } else {
                throw new RuntimeException("can not split library path:"
                        + libpath);
            }
            // 把dll文件写入到java.library.path中该dll放在ConvertWord2HM相同目录下,这个可以是你的类名
            InputStream inputStream = XinLang.class.getResourceAsStream(
                    dll);
            final File dllFile = new File(dll);
            if (!dllFile.exists()) {
                FileOutputStream outputStream = new FileOutputStream(dllFile);
                byte[] array = new byte[1024];
                int bytesRead = -1;
                while ((bytesRead = inputStream.read(array)) != -1) {
                    outputStream.write(array, 0, bytesRead);
                }
                outputStream.flush();
                outputStream.close();
            }
            // 动态加载dll
            System.load(dllFile.getPath());
            // 在虚拟机关闭的时候删除dll
            dllFile.deleteOnExit();
        }catch (Throwable e) {
            throw new RuntimeException("load Convert.dll error!", e);
        }
    }


    public static List<DataInfo> resultData(String url){
        String data = doGet(url);
        if(data == null || "".equals(data)){
            System.out.println("没有结果");
            return null ;
        }
        JSONObject jsonObject = JSON.parseObject(data) ;
        JSONObject resultJson = jsonObject.getJSONObject("result");
        JSONObject statusJson = resultJson.getJSONObject("status");
        if(!"OK".equals(statusJson.getString("msg")) && !"0".equals(statusJson.getString("code"))){
            System.out.println(resultJson);
            System.out.println("查询失败");
            return null;
        }
        JSONObject dataJson = resultJson.getJSONObject("data");
        if( "".equals(dataJson)){
            System.out.println("data" + dataJson);
            System.out.println("无结果");
            return null;
        }
       // System.out.println(dataJson.getString("feed"));
        JSONArray array = dataJson.getJSONObject("feed").getJSONArray("list");
        List<DataInfo> list = new ArrayList<>();
        for(int i = 0 ; i< array.size() ; i++){
            JSONObject listJson = array.getJSONObject(i);
            DataInfo dataInfo  = new DataInfo();
            dataInfo.setTag(listJson.getJSONArray("tag").getJSONObject(0).getString("name"));
            dataInfo.setText(listJson.getString("rich_text"));
            dataInfo.setCrateTime(listJson.getString("create_time"));
            dataInfo.setUrl(listJson.getString("docurl"));
            list.add(dataInfo);
        }
        return list;
    }


    public static String doGet(String httpurl) {
        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        String result = null;// 返回结果字符串
        try {
            // 创建远程url连接对象
            URL url = new URL(httpurl);
            // 通过远程url连接对象打开一个连接,强转成httpURLConnection类
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接方式:get
            connection.setRequestMethod("GET");
            // 设置连接主机服务器的超时时间:15000毫秒
            connection.setConnectTimeout(15000);
            // 设置读取远程返回的数据时间:60000毫秒
            connection.setReadTimeout(60000);
            // 发送请求
            connection.connect();
            // 通过connection连接,获取输入流
            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                // 封装输入流is,并指定字符集
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                // 存放数据
                StringBuffer sbf = new StringBuffer();
                String temp = null;
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
                result = sbf.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            connection.disconnect();// 关闭远程连接
        }

        return result;
    }





    static class DataInfo {
        private String text;
        private String crateTime;
        private String url;
        private String tag;

        public String getText() {
            return text;
        }

        public void setText(String text) {
            this.text = text;
        }

        public String getCrateTime() {
            return crateTime;
        }

        public void setCrateTime(String crateTime) {
            this.crateTime = crateTime;
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }

        public String getTag() {
            return tag;
        }

        public void setTag(String tag) {
            this.tag = tag;
        }
    }





    /**
     * 语音转文字并播放
     *
     *
     */
    public static void textToSpeech(String text) {

        String pathWav = path +"2926.wav" ;


        try {
            AudioPlayer.player.start(new FileInputStream(pathWav));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        ActiveXComponent ax = null;
        try {
            ax = new ActiveXComponent("Sapi.SpVoice");

            // 运行时输出语音内容
            Dispatch spVoice = ax.getObject();
            // 音量 0-100
            ax.setProperty("Volume", new Variant(100));
            // 语音朗读速度 -10 到 +10
            ax.setProperty("Rate", new Variant(-2));
            // 执行朗读
            Dispatch.call(spVoice, "Speak", new Variant(text));

            // 下面是构建文件流把生成语音文件

            ax = new ActiveXComponent("Sapi.SpFileStream");
            Dispatch spFileStream = ax.getObject();

            ax = new ActiveXComponent("Sapi.SpAudioFormat");
            Dispatch spAudioFormat = ax.getObject();

            // 设置音频流格式
            Dispatch.put(spAudioFormat, "Type", new Variant(22));
            // 设置文件输出流格式
            Dispatch.putRef(spFileStream, "Format", spAudioFormat);
            // 调用输出 文件流打开方法,创建一个.wav文件
            Dispatch.call(spFileStream, "Open", new Variant("./text.wav"), new Variant(3), new Variant(true));
            // 设置声音对象的音频输出流为输出文件对象
            Dispatch.putRef(spVoice, "AudioOutputStream", spFileStream);
            // 设置音量 0到100
            Dispatch.put(spVoice, "Volume", new Variant(100));
            // 设置朗读速度
            Dispatch.put(spVoice, "Rate", new Variant(50));

            // 开始朗读
            Dispatch.call(spVoice, "Speak", new Variant(text));

            // 关闭输出文件
            Dispatch.call(spFileStream, "Close");
            Dispatch.putRef(spVoice, "AudioOutputStream", null);

            spAudioFormat.safeRelease();
            spFileStream.safeRelease();
            spVoice.safeRelease();
            ax.safeRelease();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值