1

I'm trying to create a game and I'm currently trying to add sounds to it but due to lack of experience I failed to do so so I'm asking for your help. How can I add a background song to my game?

MrSilent
  • 564
  • 10
  • 28

2 Answers2

0

start a separate thread for playing sound. In this thread play it. In this way your game will be running and at same time you can run the sound.

public static synchronized void playSound(final String url) {
  new Thread(new Runnable() {
  // The wrapper thread is unnecessary, unless it blocks on the
  // Clip finishing; see comments.
    public void run() {
      try {
        Clip clip = AudioSystem.getClip();
        AudioInputStream inputStream = AudioSystem.getAudioInputStream(
          Main.class.getResourceAsStream("/path/to/sounds/" + url));
        clip.open(inputStream);
        clip.start(); 
      } catch (Exception e) {
        System.err.println(e.getMessage());
      }
    }
  }).start();
}
faisalbhagat
  • 2,142
  • 24
  • 27
0
public static void music() {  
            AudioPlayer MGP = AudioPlayer.player;  
            AudioStream BGM;  
            AudioData MD;  
            ContinuousAudioDataStream loop = null;  

            try {  
                BGM = new AudioStream(new FileInputStream("som.wav"));  
                MD = BGM.getData();  
                loop = new ContinuousAudioDataStream(MD);  
            } catch(IOException error)  {  
                System.out.println("Error!!!");  

            }  
            MGP.start(loop);  
        }