File formats
Java can only play the following format sound files: WAV, AU ,AIFF
File locations
Place the sounds (as WAV files) in a folder located under the project folder, e.g. GameSounds
in Java ...
List the path to the sound:
String barkFilename = ".\\GameSounds\\bark.wav";
Methods
It's convenient to make a method to play a sound, just send it the name of the file
playSound(barkFilename);
The method:
void playSound(String soundName) { try { AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File(soundName).getAbsoluteFile()); Clip clip = AudioSystem.getClip(); clip.open(audioInputStream); clip.start(); } catch(UnsupportedAudioFileException | IOException | LineUnavailableException ex) { System.out.println("Error with playing sound."); ex.printStackTrace( ); } }
Other notes:
Sound problems
Some wave files work and others do not. Why? There is some problem with the CODEC. Solution: convert to MP3 and then convert back to WAV.
Improvement?** I haven't tested this yet **
If the sound slows your program down too much, you can make the clips global variables instead of the strings for the filenames.
e.g. instead of String barkFilename = ".\\GameSounds\\bark.wav";
this would be the global variable Clip barkClip = ....
That way the getAudioInput stuff can be put into setup() and is done before the game actually starts.