网址是来自 Google 翻译的声音文件。为了防止滥用 Google 服务,服务器会执行一些启发式检查,以尝试判断访问 URL 的是人工还是自动服务。这就是它回复 403 的原因,这实际上意味着“禁止”。
免责声明:考虑他们为什么禁止它并检查他们的使用条款。
直接在 Chrome 等浏览器中打开 URL 是可行的。使用 wget 或类 URL 等工具检索 URL 不会 - 至少不是开箱即用的。
您需要更改 HTTP 请求的 User-Agent 属性才能伪造不同的用户代理。您可以通过“手动”连接并更改“用户代理”请求属性来做到这一点。
以下WGet.java 清单演示了如何执行此操作:
import java.io.*;
import java.net.*;
public class WGet {
public static void main(final String... args) throws IOException {
for (final String arg : args) {
wget(arg);
}
}
public static void wget(final String arg) throws IOException {
wget(new URL(arg));
}
public static void wget(final URL url) throws IOException {
final URLConnection con = url.openConnection();
con.setRequestProperty("User-Agent", "My Client");
try (final InputStream in = con.getInputStream()) {
copy(in, System.out);
}
}
public static void copy(final InputStream in, final OutputStream out) throws IOException {
final byte[] buf = new byte[4096];
for (int bytesRead; (bytesRead = in.read(buf)) != -1; )
out.write(buf, 0, bytesRead);
out.flush();
}
}
AudioSystem 也可以与InputStream 一起使用。所以,下面的aplay() 方法应该可以工作:
public static void aplay(String url) throws UnsupportedAudioFileException, IOException, LineUnavailableException {
Clip c = AudioSystem.getClip();
AudioInputStream a = AudioSystem.getAudioInputStream(openStream(url));
Clip c = AudioSystem.getClip();
c.open(a);
c.start();
}
public static InputStream openStream(String url) throws IOException {
final URL url = new URL(url);
final URLConnection con = url.openConnection();
con.setRequestProperty("User-Agent", "My Client");
return con.getInputStream();
}
免责声明:我正在向您展示技术解决方案。如果您将此代码添加到您的程序并使用它从 Google 获取声音文件,您实际上可能违反了 Google Translate 的使用条款。在您在产品中使用此代码从 Google 翻译获取声音文件之前,请先获取相关法律建议。