我正在开展一个项目,使用 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文件吗?你能帮我解决这个问题吗?谢谢
最佳答案
试试这个:
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();
}
关于java - 如何将音频输入流从谷歌翻译转换为 wav 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25934505/