0

I made this the classes given below to implement sounds in a game.

On execution i get the following error.

Please can some-one tell me why i'm getting this error and how to solve it!!

This is my Sound-Class file:

package flappyLemon.model.game;

import javax.sound.sampled.*;

public class Sound {

   private Clip clip;

   public static Sound sound = new Sound("LemonTree.mp3");

   public Sound(String fileName) {
         try {
                AudioInputStream ais = AudioSystem.getAudioInputStream(Sound.class.getResource(fileName));

                clip = AudioSystem.getClip();
                clip.open(ais);
         } catch (Exception e) {
                e.printStackTrace();
         }
   }

   public void play() {
         try {
                if (clip != null) {
                       new Thread() {
                              public void run() {
                                    synchronized (clip) {
                                           clip.stop();
                                           clip.setFramePosition(0);
                                           clip.start();
                                    }
                              }
                       }.start();
                }
         } catch (Exception e) {
                e.printStackTrace();
         }
   }
}

Now i call it:

Sound.sound.play();

And then I became a NullPointerException:

java.lang.NullPointerException
at com.sun.media.sound.StandardMidiFileReader.getSequence(StandardMidiFileReader.java:207)
at javax.sound.midi.MidiSystem.getSequence(MidiSystem.java:841)
at com.sun.media.sound.SoftMidiAudioFileReader.getAudioInputStream(SoftMidiAudioFileReader.java:178)
at javax.sound.sampled.AudioSystem.getAudioInputStream(AudioSystem.java:1147)
at flappyLemon.model.game.Sound.<init>(Sound.java:13)
at flappyLemon.model.game.Sound.<clinit>(Sound.java:9)
at flappyLemon.model.FlappyLemon.main(FlappyLemon.java:67)
Luca
  • 209
  • 2
  • 10

2 Answers2

1

Copy your audio source file into your project

like this:
example screen shot

Java api does not allow .mp3 files . you should use .wav files.

private Clip clip;

   public static Sound sound = new Sound("Yamaha-TG100-Whistle-C5.wav");

   public Sound(String fileName) {
         try {
                AudioInputStream ais = AudioSystem.getAudioInputStream(Sound.class.getResource(fileName));

                clip = AudioSystem.getClip();
                clip.open(ais);
         } catch (Exception e) {
                e.printStackTrace();
         }
   }

for more information click here

Community
  • 1
  • 1
Venu
  • 348
  • 4
  • 17
0

Java doesn't Support mp3 files, mp3 is a Container for Audio, which most be encoded to use.

Quote from developer.com:

Java Sound supports a wide variety of file types including AIFF, AU, and WAV. It can render both 8- and 16-bit audio data in sample rates from 8 KHz to 48 KHZ.

Meister96Fels
  • 508
  • 1
  • 8
  • 26