如何将音频inpustream从谷歌翻译转换为wav文件?

时间:2014-09-19 12:59:20

标签: java

我正在开展一个项目,使用Google API进行文字转发:https://code.google.com/p/java-google-translate-text-to-speech/。我使用了部分中的代码"播放翻译文本"。该项目运作良好。然后我想从谷歌翻译收到的输入流创建一个wav文件。我试过这个代码:

try {
        sound = audio.getAudio(text_, Language.FRENCH);
        AudioInputStream ais;
        ais = new AudioInputStream(sound,format,sound.available());
        //ais = AudioSystem.getAudioInputStream(sound);
        //AudioInputStream lowResAIS = AudioSystem.getAudioInputStream(format, ais);
        AudioFormat aisformat = ais.getFormat();
        System.out.println(aisformat.toString());
        AudioSystem.write(ais, Type.WAVE, NewfilePath);}
} catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

但我的wav文件不起作用,当我双击播放它时,它没有声音。有没有人试图将从谷歌翻译收到的音频转换为java中的wav文件?你能帮我解决这个问题吗?感谢

1 个答案:

答案 0 :(得分:0)

试试这个:

public static void main(String[] args) throws IOException   {
        String text ="hello hi how are you";
         URL url = new URL("http://translate.google.com/translate_tts?" + "q="
                 + text.replace(" ", "%20") + "&tl=" + "en");
 URLConnection urlConn = url.openConnection();
 urlConn.addRequestProperty("User-Agent",
                 "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
  InputStream audioSrc = urlConn.getInputStream();

  DataInputStream read = new DataInputStream(audioSrc);
  OutputStream outstream = new FileOutputStream(new File("src/savedSound.wav"));
  byte[] bArr = new byte[audioSrc.available()];
  int len;
  while ((len = read.read(bArr)) > 0) {
          outstream.write(bArr, 0, len);                    
  }
  outstream.close();   
    }