0
我用Vorbis的SPI發揮的Ogg文件,但我得到這個例外如何在Java中播放Ogg文件?
javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input file
at javax.sound.sampled.AudioSystem.getAudioInputStream(AudioSystem.java:1189)
at application.OggPlayer.play(OggPlayer.java:31)
at application.OggPlayer.main(OggPlayer.java:23)
這裏是文檔鏈接http://www.javazoom.net/vorbisspi/documents.html
在這裏,如果我的代碼
public class OggPlayer {
static OggPlayer player;
public static void main(String[] args) {
player = new OggPlayer();
player.play(System.getProperty("user.dir")+ "/myFile.ogg");
}
public void play(String filePath) {
try
{
File file = new File(filePath);
// Get AudioInputStream from given file.
AudioInputStream in= AudioSystem.getAudioInputStream(file);
AudioInputStream din = null;
if (in != null)
{
AudioFormat baseFormat = in.getFormat();
AudioFormat decodedFormat = new AudioFormat(
AudioFormat.Encoding.PCM_SIGNED,
baseFormat.getSampleRate(),
16,
baseFormat.getChannels(),
baseFormat.getChannels() * 2,
baseFormat.getSampleRate(),
false);
// Get AudioInputStream that will be decoded by underlying VorbisSPI
din = AudioSystem.getAudioInputStream(decodedFormat, in);
// Play now !
rawplay(decodedFormat, din);
in.close();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
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;
}
}
是否有任何錯誤用我的代碼?提前致謝。
我首先建議你檢查是否你得到你的程序中正確的文件。爲此,你可以打印文件路徑,哪一行是拋出異常? – Sikorski