我一直在努力用Java制作我的第一个GUI音乐播放器。到目前为止,我已经能够使用Javasound和MP3SPI播放MP3。现在,我想支持.m4a歌曲,并且从我研究过的最好的库中做到这一点就是JAAD。我下载了它,将它添加到我的项目中,当我尝试播放.m4a歌曲时,它工作得很好。当我在添加JAAD库后尝试播放.mp3时会出现问题。我播放歌曲的代码是:
File file = new File(pathToSong);
AudioInputStream audioStream= AudioSystem.getAudioInputStream(file); // Obtains an audio input stream of the song
AudioFormat baseFormat = audioStream.getFormat(); //Obtains the audio format of the song in the audio input stream.
decodedFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, //The type of encoding for the audio stream
baseFormat.getSampleRate(), //Sample rate of the audio stream
16, //Number of bits in each sample of a sound that has this format.
baseFormat.getChannels(), //Number of audio channels in this audio stream
baseFormat.getChannels() * 2, //Number of bytes in each frame of the audiostream
baseFormat.getSampleRate(), //Number of frames played or recorded per second, for the sound in the audio stream
false); //Data stored in little-endian order
decodedAudioStream = AudioSystem.getAudioInputStream(decodedFormat, audioStream); //Obtains an audio input stream of the indicated encoding by converting the provided audio input stream.
playSong(); //Play the song
(playSong()只是读取流并将字节写入SourceDataLine)
我在添加JAAD库后尝试播放.mp3时遇到的错误如下:
java.io.IOException: Resetting to invalid mark
at java.io.BufferedInputStream.reset(BufferedInputStream.java:416)
at net.sourceforge.jaad.spi.javasound.AACAudioFileReader.getAudioInputStream(AACAudioFileReader.java:118)
at net.sourceforge.jaad.spi.javasound.AACAudioFileReader.getAudioInputStream(AACAudioFileReader.java:143)
at javax.sound.sampled.AudioSystem.getAudioInputStream(AudioSystem.java:1162)
at Song.run(Song.java:38)
根据我的理解,似乎Javasound和JAAD的getAudioInputStream是冲突的。我该如何解决这个冲突?
答案 0 :(得分:1)
我找到了一个解决方案,根据这里的答案中的berry150代码,使用MP3SPI和JAAD:JAAD stopping other providers from working。 首先,您必须在类路径中对jar进行排序,以便在JAAD之前加载JLayer,MP3SPI和Tritonous Share。然后,要获取AudioInputStream,请使用以下代码:
if (getAudioFormat().equals(".mp3")) {
audioStream = AudioSystem.getAudioInputStream(file); // Obtains an audio input stream of the song
}
else if (getAudioFormat().equals(".m4a")){
audioStream = new AACAudioFileReader().getAudioInputStream(file);
}
所以会发生的是,如果音频是mp3,那么Javasound的getAudioStreamMethod()将首先被调用,因为它首先加载了JAR。如果音频是.m4a,则会创建一个新的ACCAudioFileReader()实例,并调用JAAD库的getAudioInputStream()。