我想要获取代码中提供的URL上的声音文件并播放(它是以
在 Eclipse 中,我将其作为外部 jar 添加到了 Build Path 中(因为它位于我的 Downloads 文件夹中,不确定是否最好放在那里)。我再次运行它,但仍然出现以下错误:
mp3
格式保存的)。我查看了一些与此问题相关的 Stack Overflow 问题,他们都建议获取 mp3plugin.jar
,所以我就这样做了。在 Eclipse 中,我将其作为外部 jar 添加到了 Build Path 中(因为它位于我的 Downloads 文件夹中,不确定是否最好放在那里)。我再次运行它,但仍然出现以下错误:
以下是代码:javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input stream
at javax.sound.sampled.AudioSystem.getAudioInputStream(Unknown Source)
at Starter.main(Starter.java:21)
public class Starter {
public static void main(String[] args) {
AudioInputStream din = null;
try {
URL url = new URL("http://c5.rbxcdn.com/2e6d33a5b3b1d8f250c395816ff9f145");
HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();
InputStream bufferedIn = new BufferedInputStream(httpcon.getInputStream());
AudioInputStream in = AudioSystem.getAudioInputStream(bufferedIn);
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) { }
}
}
}
}
mp3plugin.jar
)。 - Andrew Thompson