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

    }