How to play Music (.mp3) in Java with AudioSystem?

时间:2016-04-04 18:01:11

标签: java audio nullpointerexception

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)

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

Java不支持mp3文件,mp3是音频容器,大多数编码使用。

引自developer.com:

  

Java Sound支持各种文件类型,包括AIFF,AU和WAV。它可以以8 KHz到48 KHZ的采样率呈现8位和16位音频数据。