好的,我通过第三种方式解决了这个问题:
我制作了“代理”servlet,用于在这个 servlet 中隐藏 google TTS Engine 所需的所有参数。在代码中演示更容易:
我将代理 servlet 的 URL(而不是 Google TTS 引擎的 URL)放到 TwiML 中。对于这个 servlet,只需要一个参数:将播放的消息。在这种情况下,我避免在 TwiML 中使用 & 符号。
...
String url = Constants.APPLICATION_URL + "/tts/" +"?" + Constants.ParamName.GREETINGS + "=" + greetings;
Play play = new Play(url);
...
这是代理 servlet(它映射到 /tts/ 路径)。向 Google TTS Engine 发出请求并从它发回响应:
...
this.greetings = request.getParameter(Constants.ParamName.GREETINGS);
InputStream input = null;
HttpURLConnection con = null;
OutputStream output = null;
try {
URL obj = new URL("http://translate.google.com/translate_tts?ie=UTF-8&q=" + URLEncoder.encode(greetings, "UTF-8") + "&tl=en-us"));
con = (HttpURLConnection) obj.openConnection();
con.setConnectTimeout(5000);
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Content-Type", "audio/mpeg");
input = con.getInputStream();
response.setContentType("audio/mpeg");
output = response.getOutputStream();
byte[] buffer = new byte[10240];
for (int length = 0; (length = input.read(buffer)) > 0;) {
output.write(buffer, 0, length);
}
}
...
当然,这看起来像一个肮脏的黑客,但我认为这比在服务器上保存临时文件要好。