使用 Java 从 URL 获取声音
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13789063/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get sound from a URL with Java
提问by javando
I'm learning english and I'd like to develop a software to help me with the pronunciation.
我正在学习英语,我想开发一个软件来帮助我发音。
There is a site called HowJSay, if you enter here: http://www.howjsay.com/index.php?word=carimmediatly you'll hear the pronunciation of the word car . I'd like to develop a software in JAVA that could play this sound without necessity of enter in the site =]
有一个叫 HowJsay 的网站,如果你在这里输入:http: //www.howjsay.com/index.php?word=car 你会立即听到 car 这个词的发音。我想用 JAVA 开发一个软件,无需进入网站就可以播放这种声音 =]
I tried this, but doesn't work =/
我试过这个,但不起作用=/
public static void main(String[] args) throws Exception {
URL url = new URL("http://www.howjsay.com/index.php?word=car");
url.openConnection();
AudioStream as = new AudioStream(url.openStream());
AudioPlayer.player.start(as);
AudioPlayer.player.stop(as);
}
Any Ideas? Please.
有任何想法吗?请。
回答by Marek
Here you go
干得好
import javax.sound.sampled.*;
import java.io.IOException;
import java.net.URL;
public class HowJSay
{
public static void main(String[] args) {
AudioInputStream din = null;
try {
AudioInputStream in = AudioSystem.getAudioInputStream(new URL("http://www.howjsay.com/mp3/"+ args[0] +".mp3"));
AudioFormat baseFormat = in.getFormat();
AudioFormat decodedFormat = new AudioFormat(
AudioFormat.Encoding.PCM_SIGNED,
baseFormat.getSampleRate(), 16, baseFormat.getChannels(),
baseFormat.getChannels() * 2, baseFormat.getSampleRate(),
false);
din = AudioSystem.getAudioInputStream(decodedFormat, in);
DataLine.Info info = new DataLine.Info(SourceDataLine.class, decodedFormat);
SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info);
if(line != null) {
line.open(decodedFormat);
byte[] data = new byte[4096];
// Start
line.start();
int nBytesRead;
while ((nBytesRead = din.read(data, 0, data.length)) != -1) {
line.write(data, 0, nBytesRead);
}
// Stop
line.drain();
line.stop();
line.close();
din.close();
}
}
catch(Exception e) {
e.printStackTrace();
}
finally {
if(din != null) {
try { din.close(); } catch(IOException e) { }
}
}
}
}
回答by Andrew Thompson
Java Soundcan play short clips easily, but supports a limited number of formats out of the box. The formats it supports by default are given by AudioSystem.getAudioFileTypes()
& that list will not include MP3.
Java Sound可以轻松播放短片,但支持的开箱即用格式数量有限。它默认支持的格式由AudioSystem.getAudioFileTypes()
&给出,该列表不包括 MP3。
The solution to the lack of support for MP3 is to add a decoder to the run-time class-path of the app. Since Java Sound works on a Service Provider Interface, it only needs to be on the class-path to be useful. An MP3 decoder can be found in mp3plugin.jar
.
不支持 MP3 的解决方案是在应用程序的运行时类路径中添加一个解码器。因为 Java Sound 在服务提供者接口上工作,所以它只需要在类路径上才有用。MP3 解码器可以在mp3plugin.jar
.
As to the code for playing the MP3, the short source on the info. page should suffice so long as the clips are short. Viz.
至于播放 MP3 的代码,信息上的简短来源。只要剪辑很短,页面就足够了。即。
import java.net.URL;
import javax.swing.*;
import javax.sound.sampled.*;
public class LoopSound {
public static void main(String[] args) throws Exception {
URL url = new URL(
"http://pscode.org/media/leftright.wav");
Clip clip = AudioSystem.getClip();
// getAudioInputStream() also accepts a File or InputStream
AudioInputStream ais = AudioSystem.
getAudioInputStream( url );
clip.open(ais);
clip.loop(Clip.LOOP_CONTINUOUSLY);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// A GUI element to prevent the Clip's daemon Thread
// from terminating at the end of the main()
JOptionPane.showMessageDialog(null, "Close to exit!");
}
});
}
}
回答by Nikolay Kuznetsov
If you don't care much about the site then you try to use Google Translate API
如果您不太关心该网站,那么您可以尝试使用 Google Translate API
try{
String word="car";
word=java.net.URLEncoder.encode(word, "UTF-8");
URL url = new URL("http://translate.google.com/translate_tts?ie=UTF-8&tl=ja&q="+word);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.addRequestProperty("User-Agent", "Mozilla/4.76");
InputStream audioSrc = urlConn.getInputStream();
DataInputStream read = new DataInputStream(audioSrc);
AudioStream as = new AudioStream(read);
AudioPlayer.player.start(as);
AudioPlayer.player.stop(as);
}
With help from here: Java: download Text to Speech from Google Translate
从这里获得帮助: Java:从谷歌翻译下载文本到语音
If for every word
the site guarantees to have mp3 file with link howjsay.com/mp3/word.mp3
then you just need to change URL to
如果每个word
站点都保证有带链接的 mp3 文件,howjsay.com/mp3/word.mp3
那么您只需要将 URL 更改为
URL url = new URL("howjsay.com/mp3/" + word + ".mp3");
URL url = new URL("howjsay.com/mp3/" + word + ".mp3");
回答by Xaethriux
If you're having issues with the code provided by Marek, make sure you're meeting this criteria:
如果您对 Marek 提供的代码有疑问,请确保您符合以下条件:
- Use a supported audio format, such as 16 bit .wav
- Make sure that the URL you're using is actually playing audio automatically.
- 使用支持的音频格式,例如 16 位 .wav
- 确保您使用的 URL 实际上是自动播放音频。
It isn't sufficient to simply reference the download page for an audio file. It has to be streaming the audio. YouTube URLs won't work, as they're videos. Audacity is a good approach to converting your audio file to a compatible 16 bit .wav file, and if you have your own domain / website, you can provide a direct link to the file from there.
仅仅参考音频文件的下载页面是不够的。它必须流式传输音频。YouTube URL 不起作用,因为它们是视频。Audacity 是将您的音频文件转换为兼容的 16 位 .wav 文件的好方法,如果您有自己的域/网站,您可以从那里提供指向该文件的直接链接。