【问题标题】:Trying to play sound from a URL Java尝试从 URL Java 播放声音
【发布时间】:2014-12-06 04:24:01
【问题描述】:

我无法从某个 URL 播放声音。

这是我当前的代码,

    public static void aplay(String url) throws
    MalformedURLException, UnsupportedAudioFileException, 
    IOException, LineUnavailableException {

      Clip c = AudioSystem.getClip();
      AudioInputStream a = AudioSystem.getAudioInputStream(new URL(url));
      Clip c = AudioSystem.getClip();
      c.open(a);
      c.start();
}

另外,我的“主要”方法中有这个方法。我将https://translate.google.com/translate_tts?ie=utf-8&tl=en&q=Hi%20There 设置为“url”,但它不起作用,它会以 403 响应(服务器返回 HTTP 响应代码:403)。我只是想知道我是否可以解决这个问题。

谢谢, 丹

【问题讨论】:

  • 403 表示禁止。一般来说,除非您有一定程度的访问权限,否则不会轻易解决此问题。
  • @rfornal 有没有替代谷歌语音链接的方法?
  • 有一些替代方案......我已经使用了一些创建培训视频,但不像您在这里所做的那样以编程方式。

标签: java url audio


【解决方案1】:

网址是来自 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 翻译获取声音文件之前,请先获取相关法律建议。

【讨论】:

    猜你喜欢
    • 2014-11-06
    • 1970-01-01
    • 2013-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多