jramirez
jramirez

Reputation: 484

How to implement audio in a Java game?

I want to add audio to my java game, but I don't know how to put it in practice. By I've read, Java only plays wav files, but this files are too big. I've read a little about JLayer, but I actually need something like soundpool in android, for handle all in game effects. Do you know how to do it? I've to build a class that does it?

Upvotes: 0

Views: 1022

Answers (2)

Phil Freihofner
Phil Freihofner

Reputation: 7910

I recommend TinySound. It supports ogg/vorbis files (a free compression format comparable to mp3, but does not require licensing as mp3 does).

http://www.java-gaming.org/topics/need-a-really-simple-library-for-playing-sounds-and-music-try-tinysound/25974/view.html

A link is provided there to the github source for this library.

It is also possible to use Java as a synthesizer (I've been dabbling with this) but I'm still working on making something 'practical' for use in a game.

Upvotes: 1

rtheunissen
rtheunissen

Reputation: 7435

Here is some code for you that I've used in a game a while back using JLayer:

public class MP3 {
  public void play(final InputStream in) {
     new Thread() {
        @Override
        public void run() {
           try {
              new Player(in).play();
           } catch (Exception e) {
              System.err.println(e.getMessage());
           }
        }
     }.start();
   }
 } 

private HashMap<String, URL> soundMap = new HashMap<String, URL>();

public void loadSounds() {
      String[] filenames = {
         "5_seconds_remaining.mp3",
         "10_seconds_remaining.mp3",
         "button_press_loud.mp3"
      };
      for (String s : filenames) {
         soundMap.put(s.substring(0, s.indexOf('.')), getClass().getResource("sounds/" + s));
      }
   }

public void playSound(String name) {
     try {
         new MP3().play(new BufferedInputStream(soundMap.get(name).openStream()));
     } catch (IOException ex) {}
}

Upvotes: 2

Related Questions