2 Replies Latest reply: Nov 30, 2009 2:04 AM by 843853 RSS

    question on sounds (getting it to play in application, not applet!!)

    843853
      Hi. I've made the basis for my game already and now i'm deciding to add some sounds into my game. Suppose you had code that uses AudioClip to play sounds:
      import java.applet.*;
      import javax.swing.*;
      import java.io.*;
      import java.net.*;
      
      public class Audioapp extends JApplet {
      
           public class Sound // Holds one audio file {
                public AudioClip song; // Sound player
                public URL songPath; // Sound path
      
                Sound(String filename) {
                    try {
                          songPath = new URL(getCodeBase(),filename); // Get the Sound URL
                          song = Applet.newAudioClip(songPath); // Load the Sound
                     } catch(Exception e){} // Satisfy the catch
                }
      
                public void playSound() {
                     song.loop(); // Play
                }
      
                public void stopSound() {
                     song.stop(); // Stop
                }
      
                public void playSoundOnce() {
                     song.play(); // Play only once
                }
           }
      
           public void init() {
                Sound testsong = new Sound("song.wav");
                testsong.playSound();
           }
      }
      When compiled, it works as an APPLET, but is there a similar way to achieve the same thing but by using an application? (my game is actually using an JFrame to create the window screen and you play through that)

      Any suggestions would be much appreciated.

      Edited by: weng001 on Sep 19, 2009 11:36 PM

      Edited by: weng001 on Sep 19, 2009 11:42 PM

      Edited by: weng001 on Sep 19, 2009 11:43 PM
        • 1. Re: question on sounds (getting it to play in application, not applet!!)
          gimbal2
          look into the Java Sound API. AudioClip can only play one sound at a time.

          http://www.jsresources.org/examples/
          • 2. Re: question on sounds (getting it to play in application, not applet!!)
            843853
            weng001, in case you haven't discovered the way to play sounds in a Java application and also to help others that don't know how to do this, here is my solution.

            In a java application you can use the package java.applet.AudioClip to do this. You also have to have a couple of java files called SoundList.java and SoundLoader.java. I will put those in this post along with the code needed to put into your main class file.


            Okay, in your main class file you will need the following imports in addition to any others you have already:
            import java.applet.AudioClip;
            import java.net.URL;
            import java.net.MalformedURLException; 
            Then you will need to declare the following global variables in your main class file:
            SoundList soundList;
               String applause = "applause.wav";   // these String vars are the ones I use, you have to have one for each sound you want to use!
               String loose = "loose.aif";
               String shuffle = "shuffle.aif";
               String win = "win.aif";
               AudioClip onceClip;
               URL codeBase;
            In my constructor, I call a function
            startLoadingSounds();
            I do this before the constructor does anything else.

            The function should be placed after the end of your constructor not in it. Here is the code for startLoadingSounds():
            public void startLoadingSounds()
               {
                    // start asynchronous sound loading
                    try {
                            codeBase = new URL("file:" + System.getProperty("user.dir") + "/sounds/");   
                                                      // user.dir gets the absolute path of your program, I keep my sounds in a sounds folder 
                                                      // so I had to add that onto the programs absolute path.
                           
                    } catch (MalformedURLException e) {
                         System.err.println(e.getMessage());
                    }
                    soundList = new SoundList(codeBase);  
                    soundList.startLoading(shuffle);                // one startLoading call for each of your sounds used in the game
                    soundList.startLoading(loose);                 // notice you use the global variables made for each sound file
                    soundList.startLoading(win);
                    soundList.startLoading(applause);
              }
            Then, each place in your main class file that you want to play a sound, add this code.
            I have a menu selection that allows the user to turn sounds on or off
            so my code to play a specific sound looks like this:
            if(soundOn == true)
                {
                    onceClip = soundList.getClip(shuffle); // this plays my card shuffle sound Note: "shuffle" corresponds to the global variable!
                                                                                      // you use the global variable of the sound you want to play
                    onceClip.play();                                       // then you tell it to play with onceClip.play();
               }
            And now, the two additional java class files you will need to add to your project for this to work are:

            SoundList.java
            import java.applet.AudioClip;
            import javax.swing.*;
            import java.net.URL;
            
            /**
             * Loads and holds audio files whose location are
             * specified relative to a fixed base URL.
             */
             
            public class SoundList extends java.util.Hashtable
            {
                 JApplet applet;
                 URL baseURL;
            
                 
                 
                 public SoundList(URL baseURL)
                 {
                      super(4); // Initialize Hashtable with capacity of 4 entries
                      
                      
                      this.baseURL = baseURL;
                 }
                 
                 public void startLoading(String relativeURL)
                 {
                      new SoundLoader(this, baseURL, relativeURL);
                 }
                 
                 public AudioClip getClip(String relativeURL)
                 {
                      return (AudioClip)get(relativeURL);
                 }
                 
                 public void putClip(AudioClip clip, String relativeURL)
                 {
                      put(relativeURL, clip);
                 }
            }
            SoundLoader.java
            import java.applet.*;
            import javax.swing.*;
            import java.net.URL;
            import java.net.MalformedURLException;
            
            public class SoundLoader extends Thread
            {
                 SoundList soundList;
                 URL completeURL;
                 String relativeURL;
                 
                 public SoundLoader(SoundList soundList,
                                    URL baseURL, String relativeURL)
                 {
                      this.soundList = soundList;
                      try {
                           completeURL = new URL(baseURL, relativeURL);
                           
                      } catch (MalformedURLException e){
                           System.err.println(e.getMessage());
                      }
                      this.relativeURL = relativeURL;
                      setPriority(MIN_PRIORITY);
                      start();
                 }
                 
                 public void run()
                 {
                      AudioClip audioClip = Applet.newAudioClip(completeURL);
                      soundList.putClip(audioClip, relativeURL);
                 }
            }
            That will allow you to easily play sounds in your java game application.