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=“+ZHTexthtml

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

<!-- 百度语音接口 -->
  <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下载转换后的文件web

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)json

@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());

    }