Reputation: 84
I am trying to make a music player in java. I have gone to numerous websites and looked at resources to see how it works, but AudioInputStream gives me a nullPointerException in a place where I least expect it! It seems that no one has asked this question before (in addition, I don't have enough rep to comment so I had to make this a separate question), so I'll show you the code where it's going wrong:
Clip clip = AudioSystem.getClip();
AudioInputStream ais = AudioSystem.getInputStream(new File("mywav.wav"));
clip.open(ais);
clip.start();
I surrounded this with Thread and started the Thread, so it should play fully. But, I get a nullPointerException at the line "AudioInputStream ais = AudioSystem.getInputStream(...."
Upvotes: 0
Views: 1044
Reputation: 7910
1) You can load your sound from where-ever. A folder called "sound" is just a convenience, such as a folder called "images" for your art graphics.
2) I think you will have better luck if you use the URL instead of the file as your input source.
Thus:
URL url = this.getClass().getResource("mywav.wav");
AudioInputStream aiStream = AudioSystem.getAudioInputStream(url);
One obscure problem that comes up (and I've helped about a dozen people making the same error) is that when you do it your way, you create the intermediate step where there is an InputStream. If you check the JavaDocs for AudioSystem.getAudioInputStream(url) vs AudioSystem.getAudioInputStream(inputStream), you will see that the InputStream has to be a "markable" file, and there are no guarantees of this. With the URL form, there is no such test or requirement.
Here are the links, for easier perusal. http://docs.oracle.com/javase/6/docs/api/javax/sound/sampled/AudioSystem.html#getAudioInputStream(java.net.URL) http://docs.oracle.com/javase/6/docs/api/javax/sound/sampled/AudioSystem.html#getAudioInputStream(java.io.InputStream)
It seems prior to Java 7, for some reason, there was a default such that the system "knew" how to handle wav files, but this default is no longer in place and many folks who used your way of getting their AudioInputStream from an InputStream suddenly found their sound code broken. There's even an offical Oracle bug report on this: #7095006
Upvotes: 1
Reputation: 1339
Try this instead
private AudioClip clip;
clip = getAudioClip(getCodeBase(), "sounds/mywav.wav");
clip.loop();
You will need to create a new folder called sounds. Then put your sound file, in the folder. Note that all your sounds have to be .wav
Upvotes: 0