2014-09-19 82 views
0

我正在制作一个项目,使用Google API对文字进行演讲:https://code.google.com/p/java-google-translate-text-to-speech/。我使用了“播放翻译文本”部分的代码。该项目运作良好。然后我想从谷歌翻译收到的输入流中创建一个wav文件。我试着用这个代码:如何将音频inpustream从谷歌翻译转换为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文件?你能帮我解决这个问题吗?由于

+0

,你得到这个工作? – user3487063 2014-09-22 12:19:29

回答

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(); 
    } 
+0

非常感谢您的代码。它运作良好 – 2014-09-25 13:41:18