[java] Adding sound/music to java game

Started by
4 comments, last by Kippesoep 18 years, 11 months ago
how do i go about adding music and sound to my java game. i basically want to add sound effects when a hit has been made and music throughout the game playing. many thanks tom :)
Advertisement
Hi.

You can add sound easily enough to a java program by using the AudioClip object contained within the applet collection of classes. It is very limited compared to using something like OpenAl but it is about the easiest way to add sound to your game.

Below is some code which I have written that will play either a .wav of .mid file using the AudioClip object. I think the code is fairly self explanatory but if you have any questions then be sure to ask:

import java.applet.AudioClip;import java.applet.Applet;import java.net.URL;import java.io.File;class MidiMusic{static AudioClip currentSound;static void endSound(){// Stop the currently played audioclipif	( currentSound != null )	{         // only stop the audioclip if it exists	currentSound.stop();	}}static void playSound(String soundFile){currentSound = loadSound(soundFile);  // load the specified .wav or .mid fileif	( currentSound != null )	{         // Only play the song if it has loaded ok	currentSound.loop();	System.out.println("Now playing audioclip:"+soundFile);	}}static AudioClip loadSound(String fileName){// loads an audioclipAudioClip loadedSound = null;  // audioclip to returntry	{	// create a file object from specified filename	File soundFile = new File(fileName);	         // must convert file path to URL for use with applet audioclip loader	URL fileURL = soundFile.toURL();	         // use the applet class to load the audioclip	loadedSound = Applet.newAudioClip(fileURL);	}	catch ( Exception e )	{	// Something went wrong loading the sound	System.out.println("Couldn't load sound '" + fileName + "'");	}return(loadedSound);  // return the sound loaded}}
this may seem like a daft question but its not an applet so what does this still apply?
Quote:Original post by TomButcher
this may seem like a daft question but its not an applet so what does this still apply?


You can use this code in either an applet or an application. You are not actually creating any applet program- just using its functions for loading and playing audioclips, thats all.
Have you checked out the Java Media Framework?

It should handle anything you throw at it media-wise. Also for more low level stuff the JavaSound API is pretty good if not yet fully supported on all platforms.

Cheers

kezz
-------------------------0 A.D.
Bear in mind that the AudioClip interface does not work properly for short sounds (<1 sec) for many Sun JVM versions up to 1.5.0 update 2.

[Edited by - Kippesoep on April 26, 2005 2:45:46 PM]
Kippesoep

This topic is closed to new replies.

Advertisement