【发布时间】:2016-01-25 00:55:37
【问题描述】:
我正在尝试让这个 Java 程序使用 URL 接收音频文件。当我这样做时,它只会给出一个错误:
javax.sound.sampled.UnsupportedAudioFileException:无法从输入流中获取音频输入流 在 javax.sound.sampled.AudioSystem.getAudioInputStream(未知来源) 在 Starter.main(Starter.java:21)
当您在浏览器中访问该 URL 时,它会下载一个不带 .mp3 扩展名的文件,该文件带有用于将其存储在数据库中的哈希值。
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.SourceDataLine;
public class Starter {
public static void main(String[] args) {
AudioInputStream din = null;
try {
URL url = new URL("http://www.roblox.com/asset/?id=138738005");
HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();
InputStream bufferedIn = new BufferedInputStream(httpcon.getInputStream());
//AudioInputStream in = AudioSystem.getAudioInputStream(Starter.class.getResourceAsStream("338876528.mp3"));
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) { }
}
}
}
}
【问题讨论】:
-
不确定这是否是您想要的,但请查看this. 编辑:由于我无法回复(低于 50 个代表),我将在此处添加此编辑。首先,就像 CaringDev 所说,它甚至根本不是音频文件。其次,我在没有 .mp3 扩展名的情况下尝试了这段代码,它运行良好。
-
url返回的文件没有.mp3扩展名,所以我不确定它是否有效。