【解決】 後端處理 google api 語音合成 回應並撥放語音

常見問題

本文提供
方法一:拿取語音後,製成檔案並下載至資料夾,再拿取語音檔至前端撥放
方法二:拿取語音後,直接至前端撥放


可先至 https://translate.google.com/translate_tts?ie=utf-8&client=tw-ob&tl=zh&q=1+2+3+4
將q的值更換,了解參數格式


解決方法:
1.前端

(1)建立 [播放按鈕] 與 [<audio>標籤],autoplay=”autoplay”為當audio執行並回傳時,會直接撥放語音

 <input type="button" class="mb5" value="語音播放" title="語音播放" onclick="javascript:getAudio();return false;">
  <audio src="" id="audio" hidden  autoplay="autoplay" ></audio>

(2)建立 [方法]

function getAudio(){

    $('#audio').removeAttr("src") ;
    var url = "<c:url value='/getAudioFromGoogleApi'/>"; //進入後端的路徑
    $('#audio').attr("src",url) ; 

}
2.後端

方法一:

下載語音檔案後,再拿取檔案回傳至前端

@RequestMapping(value = "/getAudioFromGoogleApi", method = RequestMethod.GET)
public void getAudioFromGoogleApi(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException {

        HttpURLConnection conn = null;

        try {
           
            //至https://translate.google.com取得合成語音
            URL url = new URL("https://translate.google.com/translate_tts?ie=utf-8&client=tw-ob&tl=zh&q="+1+2+3+4);

            conn = (HttpURLConnection) url.openConnection();
            conn.addRequestProperty("User-Agent", "Mozilla/4.76");
            InputStream audioSrc = conn.getInputStream();
            DataInputStream read = new DataInputStream(audioSrc);

            //將回來的語音寫入檔案
            OutputStream outstream = new FileOutputStream( "D:\\"+ new File(str+".mp3"));
            byte[] buffer = new byte[1024];
            int len;
            while ((len = read.read(buffer)) > 0) {
                    outstream.write(buffer, 0, len);                    
            }
            outstream.close();   

            //斷開連線,釋放資源
            conn.disconnect();
                        
        }catch( IOException e ) {
            e.printStackTrace();

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

        } finally {
            //關閉連線,釋放資源
            if (null != conn) {
                conn.disconnect();
            }
  
        }
     
     //取得已下載的檔案回傳至前端
     File file = new File("D:\\"+str+".mp3");
        if (file.exists()) {

            String mimeType = URLConnection.guessContentTypeFromName(file.getName());
            if (mimeType == null) {
                mimeType = "application/octet-stream";
            }

            response.setContentType(mimeType);
            response.setHeader("Content-Disposition", String.format("inline; filename=\"" + file.getName() + "\""));


           //將檔案內容拷貝到一個輸出流中
            response.setContentLength((int) file.length());
            InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
            FileCopyUtils.copy(inputStream, response.getOutputStream());
        }
        
    }

方法二:

下載語音檔案後,直接回傳至前端

@RequestMapping(value = "/getAudioFromGoogleApi", method = RequestMethod.GET)
public void getAudioFromGoogleApi(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException {
  

        HttpURLConnection conn = null;

        try {
   
           //至https://translate.google.com取得合成語音

            URL url = new URL("https://translate.google.com/translate_tts?ie=utf-8&client=tw-ob&tl=zh&q="+1+2+3+4);

            conn = (HttpURLConnection) url.openConnection();
            conn.addRequestProperty("User-Agent", "Mozilla/4.76");
            InputStream audioSrc = conn.getInputStream();
            DataInputStream read = new DataInputStream(audioSrc);

            //將內容拷貝到一個輸出流中
            FileCopyUtils.copy(read , response.getOutputStream());

            //斷開連線,釋放資源
            conn.disconnect();

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

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

        } finally {
            //關閉連線,釋放資源
            if (null != conn) {
                conn.disconnect();
            }
  
        }


        
    }

Related Posts

One thought on “【解決】 後端處理 google api 語音合成 回應並撥放語音

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js