在发布之前我已经搜索了论坛(我没有找到我的问题的答案,因此发表了这篇文章)。我想制作一个 java 应用程序,它可以播放来自广播服务器的音频流。我在网上查看过,发现 javazoom 对我想做的事情很有用。所以我下载了他们的包并开始实验。我想出了这个,但我得到一个“javax.sound.sampled.UnsupportedAudioFileException:无法从输入 URL 获取音频输入流”
这是代码:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package test;
/**
*
* @author George
*/
import java.io.*;
import java.util.Map;
import java.net.*;
import javax.sound.sampled.*;
public class play {
public void testPlay(String filename)
{
try {
// File file = new File(filename);
URL file= new URL(filename);
AudioInputStream in= AudioSystem.getAudioInputStream(file);
AudioInputStream din = null;
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);
// Play now.
rawplay(decodedFormat, din);
in.close();
din = AudioSystem.getAudioInputStream(decodedFormat, in);
// DecodedMpegAudioInputStream properties
if (din instanceof javazoom.spi.PropertiesContainer)
{
Map properties = ((javazoom.spi.PropertiesContainer) din).properties();
float[] equalizer = (float[]) properties.get("mp3.equalizer");
equalizer[0] = (float) 0.5;
equalizer[31] = (float) 0.25;
}
} catch (Exception e)
{
System.out.println(e);
}
}
private void rawplay(AudioFormat targetFormat, AudioInputStream din) throws IOException, LineUnavailableException
{
byte[] data = new byte[4096];
SourceDataLine line = getLine(targetFormat);
if (line != null)
{
// Start
line.start();
int nBytesRead = 0, nBytesWritten = 0;
while (nBytesRead != -1)
{
nBytesRead = din.read(data, 0, data.length);
if (nBytesRead != -1) nBytesWritten = line.write(data, 0, nBytesRead);
}
// Stop
line.drain();
line.stop();
line.close();
din.close();
}
}
private SourceDataLine getLine(AudioFormat audioFormat) throws LineUnavailableException
{
SourceDataLine res = null;
DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
res = (SourceDataLine) AudioSystem.getLine(info);
res.open(audioFormat);
return res;
}
}