Search code examples
javaaudiojavasound

Adding Music To Java


I'm making connect four for my high school cpt and I'm trying to add music to the background and for sound effects. My teacher gave me some code to work with, but since I have never worked with sound I don't understand how to use it. Can someone please explain the code that I was given? Thanks for your help!

try {
  AudioInputStream audio = AudioSystem.getAudioInputStream(new File("SoundFile.wav"));//use wav. mp3 doesn't work
  Clip clip = AudioSystem.getClip();
  clip.open(audio);
  clip.start();
} 
catch(UnsupportedAudioFileException uae) {
  System.out.println(uae);
} 
catch(IOException ioe) { 
  System.out.println(ioe);
} 
catch(LineUnavailableException lua) { 
  System.out.println(lua);
}

Solution

  • You need to import the following classes from the relevant packages:

    AudioInputStream 
    UnsupportedAudioFileException
    IOException 
    LineUnavailableException
    File