从使用Java的URL获取声音 [英] Get sound from a URL with Java
本文介绍了从使用Java的URL获取声音的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我学英语,我想开发一个软件来帮助我的发音。
I'm learning english and I'd like to develop a software to help me with the pronunciation.
有一个名为HowJSay网站,如果你在这里输入: HTTP:// WWW。 howjsay.com/index.php?word=car
立刻,你会听到字车的发音。我想用Java开发一个软件,可以玩这个声音没有在网站上输入的必要性=]
There is a site called HowJSay, if you enter here: http://www.howjsay.com/index.php?word=car immediatly 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 =]
我想这一点,但不工作= /
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);
}
任何想法?请。
推荐答案
在这里你去
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) { }
}
}
}
}
这篇关于从使用Java的URL获取声音的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文