TTS文件转语音接口简单Demo(百度文字转语音免费接口)

1.主要是调用百度语音免费接口,把需要的文字转换为语音文件,并且返回文件全路径名称。
2.要注意在调用的时候注意编码,不然可能中文转换语音失败的问题
3.调用百度提供的公网接口: http://tts.baidu.com/text2audio?lan=zh&ie=UTF-8&spd=5&text=你要转换的文字
4.我的放在本地服服务器上,所以我的调用方式如下:http://localhost:8080/BaiduYYInterface/BaiduYYInterface?text=“+ZHText

1.web.xml配置文件的书写(语音速度和mp3文件下载路径)

  <!-- 百度语音接口  -->
  <servlet>
    <servlet-name>BaiduYYInterface</servlet-name>
    <servlet-class>etcom.BaiduYYInterface</servlet-class>
     <init-param>
        <param-name>speed</param-name>
        <param-value>5</param-value>
     </init-param>
     <init-param>
        <param-name>downDir</param-name>
        <param-value>C:/Users/etcom/Desktop</param-value>
     </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>BaiduYYInterface</servlet-name>
    <url-pattern>/BaiduYYInterface</url-pattern>
  </servlet-mapping>

2.http下载转换后的文件

  public static File downloadFile(String urlPath, String downloadDir) {
        File file = null;
        HttpURLConnection httpURLConnection = null;
        BufferedInputStream bin = null;
        OutputStream out = null;

        try {
            // 统一资源
            URL url = new URL(urlPath);
            // 连接类的父类,抽象类
            URLConnection urlConnection = url.openConnection();
            // http的连接类
            httpURLConnection = (HttpURLConnection) urlConnection;
            // 设定请求的方法,默认是GET
            httpURLConnection.setRequestMethod("POST");
            // 设置字符编码
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            // 打开到此 URL 引用的资源的通信链接(如果尚未建立这样的连接)。
            httpURLConnection.connect();

            //获取相应码
            int responseCode = httpURLConnection.getResponseCode();
            if(responseCode!=200){
                return null;
            }

            // 文件大小
            int fileLength = httpURLConnection.getContentLength();

            // 文件名
            //String filePathUrl = httpURLConnection.getURL().getFile();
            //String fileFullName = filePathUrl.substring(filePathUrl.lastIndexOf(File.separatorChar) + 1);

            System.out.println("file length---->" + fileLength);

            bin = new BufferedInputStream(httpURLConnection.getInputStream());

            //String path = downloadDir + File.separatorChar + fileFullName;
            //文件名称
            Date d = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String fileName = sdf.format(d)+".mp3";
            String path = downloadDir + File.separatorChar +fileName;
            file = new File(path);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            out = new FileOutputStream(file);
            int size = 0;
            int len = 0;
            byte[] buf = new byte[1024];
            while ((size = bin.read(buf)) != -1) {
                len = len+size;
                out.write(buf, 0, size);
                // 打印下载百分比
                // System.out.println("下载了-------> " + len * 100 / fileLength +
                // "%\n");
            }
            System.out.println(file.getAbsolutePath()+"--下载成功");
            bin.close();
            out.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //释放资源
            try {
               if (bin!=null) {
                   bin.close();
                }
               if (out!=null) {
                   out.close();
               }
               if (httpURLConnection!=null) {
                   httpURLConnection.disconnect();
                   httpURLConnection = null;
               }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file;
    }

3.接口的调用(servlet)

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        StringBuffer sb = new StringBuffer();
        response.setContentType("text/html");
        //获取ServletConfig对象,根据参数名获取参数值
        ServletConfig config = this.getServletConfig();
        String speed = config.getInitParameter("speed");
        String downDir = config.getInitParameter("downDir")==null?"":config.getInitParameter("downDir");
        //获取请求参数
        String text = request.getParameter("text");
        JSONObject jo = new JSONObject();
        try {
            if(text!=null && text.length()>0){
                //先替换text,空格和换行符,让语速变得动听
                text = text.replaceAll(" ", ",");
                text = text.replaceAll("\n", "。");
                //调用url
                String url = "http://tts.baidu.com/text2audio?lan=zh&ie=UTF-8&spd="+speed+"&text="+java.net.URLEncoder.encode(text,"utf-8");
                //File downloadFile = HttpUtils.downloadFile(java.net.URLEncoder.encode(url,"gb2312"), "/download");
                File downloadFile = HttpUtils.downloadFile(url, downDir);
                if(downloadFile!=null){
                    sb.append(downloadFile.getAbsolutePath());
                    jo.put("name", sb.toString());

                }else{
                    jo.put("name", "转换失败");
                }
            }else{
                jo.put("name", "转换文字为空");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        response.setContentType("text/json");
        response.getWriter().println(jo.toString());

    }
  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值