July 20, 2011

Java Audio

I have to say, Java really doesn't make playing audio simple and intuitive. It isn't overly complicated, but I expected it to be as easy as loading images, apparently not. I will have to check to make sure the Applet is loading the audio file from the jar and not trying to download the song from my website every time someone runs the applet (I have a feeling that could get costly).

If all goes well not only will I have background music but also sound effects. For anyone that is interested this is the code required to play wav files: (mp3 requires a third-party library)


import java.applet.Applet;
import java.applet.AudioClip;
import java.net.URL;


public class SimpleAudio {
  public static void main(String[] args) {
    try {
      Applet.newAudioClip(new URL("YOUR_FILE_PATH_HERE.wav")).play();
    } catch (MalformedURLException e) {}
  }
}

As you call tell... why not abuse the high-level API of Applet to do the dirty work? Java will automatically mix multiple AudioClips, and unlike Clip, AudioClip doesn't appear to have a length limit. Turns out to be a very easy way to do something apparently complicated in Java.

The above is obviously not code I would use for anything practical, but it is simply a way to hopefully show someone how easy audio can be added to a Java application. Now, before people ask me what 3rd-party library they need for mp3... go here: http://www.javazoom.net/mp3spi/mp3spi.html

I was going to tell the guy he should thread his Player play() method so that it is non-blocking, but it is simple enough to workaround I really doubt it is a useful suggestion. I guess a short example to prove my point:


import java.io.InputStream;
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;

public class ThreadedPlayer extends Player implements Runnable {
    public ThreadedPlayer(InputStream arg0) throws JavaLayerException {
        super(arg0);
    }
 
    public void play() {
        new Thread(this).start();
    }

    @Override public void run() {
        try {
            super.play();
        } catch (JavaLayerException e) {
            e.printStackTrace();
        }
    }  
}


Okay, good enough for me. Yes, calling close() will unblock play and exit the thread. :P

No comments :

Post a Comment