I create a class to create AudioPlayer
package Audio;
import javax.sound.sampled.*;
public class AudioPlayer {
private Clip clip;
public AudioPlayer(String s) {
try {
AudioInputStream ais = AudioSystem.getAudioInputStream(getClass().getResourceAsStream(s));
AudioFormat baseFormat = ais.getFormat();
AudioFormat decodeFormat = new AudioFormat(
AudioFormat.Encoding.PCM_SIGNED,
baseFormat.getSampleRate(),
16,
baseFormat.getChannels(),
baseFormat.getChannels() * 2,
baseFormat.getSampleRate(),
false
);
AudioInputStream dais =
AudioSystem.getAudioInputStream(
decodeFormat, ais);
clip = AudioSystem.getClip();
clip.open(dais);
}
catch(Exception e) {
e.printStackTrace();
}
}
public void play() {
if(clip == null) return;
stop();
clip.setFramePosition(0);
clip.start();
}
public void stop() {
if(clip.isRunning()) clip.stop();
}
public void close() {
stop();
clip.close();
}
}
So I try to put it in the menu of my game (GameState):
[...]
import Audio.AudioPlayer;
[...]
private AudioPlayer bgMusic;
[...]
bgMusic = new AudioPlayer("Resources/Musics/menu.mp3");
bgMusic.play();
And then I get this error:
java.lang.NullPointerException
at javazoom.spi.mpeg.sampled.file.MpegAudioFileReader.getAudioInputStream(Unknown Source)
at javax.sound.sampled.AudioSystem.getAudioInputStream(Unknown Source)
at Audio.AudioPlayer.<init>(AudioPlayer.java:13)
at GameState.MenuState.<init>(MenuState.java:38)
at GameState.GameStateManager.loadState(GameStateManager.java:30)
at GameState.GameStateManager.<init>(GameStateManager.java:24)
at main.GamePanel.init(GamePanel.java:64)
at main.GamePanel.run(GamePanel.java:70)
at java.lang.Thread.run(Unknown Source)
Can anyone help me ???
EDIT:
I had JDK 7, I installed 8, because of JavaFX, but I have a problem with 8 ... that's another story ...
But, I got this AudioPlayer of this video:
And he used a song in MP3, so I'm kind of dubious ....