How to implement audio in a Java game?

自古美人都是妖i 提交于 2019-12-12 03:04:29

问题


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?


回答1:


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) {}
}



回答2:


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.



来源:https://stackoverflow.com/questions/16087152/how-to-implement-audio-in-a-java-game

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!