Skip to main content
GameDev.net gamedev.net
🔒 Locked

Sound In My Java Game

Started by NickyP101 Apr 4, 2005 at 6:40 AM 2 replies 1.2k views
Original Post
NickyP101
NickyP101
Programming Lang: Java Can someone please give me a simple peice of code playing a simple wav or mp3 file. I left adding sound to my game till last, ive tried the OpenAL Java bindings but they dont work, too many bugs, ive looked at javax.sound.sampled.* package but i hvnt found enough tutorials on that to get me started. All i want to do is beable to play sounds in my game lol Please any help? I need to be able to play sounds concurently, and i wouldnv'e loved to be able to "position" sound but i think that opportunity as pased me as Java OpenAL did not work for me. Thanks for any help. Cheers, Nick
Luckless
Luckless
Have you looked over the Sun website? All you really should need is to look up the part of the standard libs there that play sounds, include the package, and have it run your sounds when you call. Its not all 'that' hard to get a basic sound file playing in Java, however, using the built in classes might not be good enough for your game. I have only used them twice. (Once to test how to play sounds in Java before I did the assignment, and again for the assignment itself)

I'm in a computer lab right now, but don't have my files. So, take a look at docs on the sun website, look it over, think about it for a few, and if you still need help (and no one else gets around to it) I'll post some stuff up here when I get home tonight. (If I think about it, I do have like 2 papers due this week I need to start.)
Old Username: Talroth
If your signature on a web forum takes up more space than your average post, then you are doing things wrong.
Aldacron
Aldacron
Quote:
Original post by NickyP101
Programming Lang: Java

Can someone please give me a simple peice of code playing a simple wav or mp3 file. I left adding sound to my game till last, ive tried the OpenAL Java bindings but they dont work, too many bugs, ive looked at javax.sound.sampled.* package but i hvnt found enough tutorials on that to get me started. All i want to do is beable to play sounds in my game lol Please any help? I need to be able to play sounds concurently, and i wouldnv'e loved to be able to "position" sound but i think that opportunity as pased me as Java OpenAL did not work for me.

Thanks for any help.

Cheers, Nick


Plenty of people are using JOAL, the OpenAL binding, just fine. Perhaps you should ask for help in the JOAL forum at javagaming.org if you are having trouble with it. Check the Java Sound forum there as well for Java Sound API issues.
Darragh
Darragh
Heres the code for my AL_Sound class. I'm not using positional sound (yet) but if you check out the sun tutorials you should be able to figure it out.

I reckon your problem might be during the initialisation of OpenAL. Check the initSound() method and see if something is missing. I had loads of problems getting this going too, so you may be missing out on the same things i did..


import net.java.games.joal.*;import net.java.games.joal.util.*;import javax.swing.JOptionPane;import java.nio.*;class AL_Sound{static AL myAL;static ALC myALC;// ERROR CHECKINGstatic boolean AL_INIT_OK = false;// SOUND NUMBERSstatic int SOUND_DOOR_OPEN 	= 0;static int SOUND_DOOR_CLOSE 	= 1;static int SOUND_FOOTSTEP_1 	= 2;static int SOUND_FOOTSTEP_2 	= 3;static int SOUND_MOVER_SWITCH 	= 4;static int SOUND_MOVER_MOVING 	= 5;// MAXIUM NUMBER OF SOUNDS AND SOURCES/CHANNELSstatic int MAX_SOUNDS  = 256;static int MAX_SOURCES = 48;// SOUND BUFFER NUMBERS AND SOURCE NUMBERSstatic int[] soundBuffers = new int[MAX_SOUNDS]; static int[] soundSources = new int[MAX_SOURCES]; // KEEP TRACK OF WHEN A SOURCE HAS BEEN PLAYED AND IF IT IS LOOPINGstatic long[] soundSourceLastMS     = new long[MAX_SOURCES];static boolean[] soundSourceLooping = new boolean[MAX_SOURCES];// DEFAULT SOURCE POSITIONstatic float[] sourcePos = { 0.0f, 0.0f, 0.0f };// DEFUALT SOURCE VELOCITYstatic float[] sourceVel = { 0.0f, 0.0f, 0.0f };static void initSound(){// Presume we don't have sound until everything is initialisedAL_INIT_OK = false;try	{	ALFactory.initialize();		myALC = ALFactory.getALC();			ALC.Device soundDevice = myALC.alcOpenDevice("DirectSound3D");	ALC.Context currentSoundContext = myALC.alcCreateContext(soundDevice,new int[] {0});	myALC.alcMakeContextCurrent(currentSoundContext);		if	( myALC.alcGetError(soundDevice) != ALC.ALC_NO_ERROR )		{		System.out.println("Error with DirectSound sound device!");		}	myAL = ALFactory.getAL();	if	( myAL.alGetError() != AL.AL_NO_ERROR )		{		System.out.println("Error with DirectSound sound device!");		}	AL_INIT_OK = true;	System.out.println("OpenAL initialised");		}catch ( OpenALException a )	{	System.out.println("Unable to initialise OpenAL sound!");	System.out.println(a.getMessage());	AL_askUpdateDLL.askUpdate();	}}static void exitSound(){	ALC.Context currentSoundContex 	= myALC.alcGetCurrentContext();ALC.Device currentSoundDevice 	= myALC.alcGetContextsDevice(currentSoundContex);myALC.alcDestroyContext(currentSoundContex);myALC.alcCloseDevice(currentSoundDevice );}static void generateBuffers(){if	( AL_INIT_OK )	{		myAL.alGenBuffers(MAX_SOUNDS,soundBuffers);		if	( ! ( myAL.alGetError() == AL.AL_NO_ERROR ) )		{		System.out.println("Error generating sound buffers");				JOptionPane.showMessageDialog			(			null,			"Error generating sound buffers for loading sounds.\n"+			"It is likely that there is not enough memory.\n"+			"Try increasing the amount of memory allocated to the program.\n"+			"You can do this by editing the 'start.bat' file.\n"+			"Adding the flag -Xmx128M for example will allocate 128MB of ram\n"+			"For the program rather than the default of 64MB",			"Error generating sound buffers",			JOptionPane.ERROR_MESSAGE			);					}			myAL.alGenSources(MAX_SOURCES,soundSources);		if	( ! ( myAL.alGetError() == AL.AL_NO_ERROR ) )		{		System.out.println("Error generating sound sources");				JOptionPane.showMessageDialog			(			null,			"Error generating specified number of channels for playing sounds.\n"+			"Your sound device and/or OpenAL does not support this number of channels\n"+			"Current number of sound channels:"+MAX_SOURCES + "\n" +			"Try lowering the amount of sound channels used and restart.",			"Could not use the specified number of sound channels",			JOptionPane.ERROR_MESSAGE			);				}		}}static void loadAllSounds(){loadSound("sounds\door_open.wav"    ,SOUND_DOOR_OPEN ,false);	loadSound("sounds\door_close.wav"   ,SOUND_DOOR_CLOSE,false);loadSound("sounds\footstep_r_1.wav" ,SOUND_FOOTSTEP_1,false);	loadSound("sounds\footstep_r_2.wav" ,SOUND_FOOTSTEP_2,false);loadSound("sounds\mover_switch.wav" ,SOUND_MOVER_SWITCH,false);loadSound("sounds\mover_moving.wav" ,SOUND_MOVER_MOVING,false);}static void playSound(int soundNumber){// GET THE CHANNEL WHICH HAS BEEN USED LONGEST AGOint currentChannel = getSoundChannelToPlay();// TIME STAMP THE CURRENT CHANNEL SO WE KNOW WHEN IT LAST PLAYEDsoundSourceLastMS[currentChannel] = System.currentTimeMillis();myAL.alSourcei (soundSources[currentChannel], AL.AL_BUFFER,   soundBuffers[soundNumber]);myAL.alSourcef (soundSources[currentChannel], AL.AL_PITCH,    1.0f     	);myAL.alSourcef (soundSources[currentChannel], AL.AL_GAIN,     1.0f     	);myAL.alSourcefv(soundSources[currentChannel], AL.AL_POSITION, sourcePos	);myAL.alSourcefv(soundSources[currentChannel], AL.AL_VELOCITY, sourceVel	);myAL.alSourcei (soundSources[currentChannel], AL.AL_LOOPING,  0 	);	if	( AL_INIT_OK )	{	myAL.alSourcePlay(soundSources[currentChannel]);	}	}static int playSoundLoop(int soundNumber){// GET THE CHANNEL WHICH HAS BEEN USED LONGEST AGOint currentChannel = getSoundChannelToPlay();// TIME STAMP THE CURRENT CHANNEL SO WE KNOW WHEN IT LAST PLAYEDsoundSourceLastMS[currentChannel] = System.currentTimeMillis();// DESIGNATE THIS CHANNEL AS BEING LOOPING SO OTHER SOUNDS WONT INTERFEREsoundSourceLooping[currentChannel] = true;myAL.alSourcei (soundSources[currentChannel], AL.AL_BUFFER,   soundBuffers[soundNumber]);myAL.alSourcef (soundSources[currentChannel], AL.AL_PITCH,    1.0f     	);myAL.alSourcef (soundSources[currentChannel], AL.AL_GAIN,     1.0f     	);myAL.alSourcefv(soundSources[currentChannel], AL.AL_POSITION, sourcePos	);myAL.alSourcefv(soundSources[currentChannel], AL.AL_VELOCITY, sourceVel	);myAL.alSourcei (soundSources[currentChannel], AL.AL_LOOPING,  1 	);	if	( AL_INIT_OK )	{	myAL.alSourcePlay(soundSources[currentChannel]);	}return(currentChannel);	}static void endSoundLoop(int channelNumber){// END THIS CHANNELS LOOPsoundSourceLooping[channelNumber] = false;if	( AL_INIT_OK )	{	myAL.alSourceStop(soundSources[channelNumber]);	}}static void loadSound(String soundName, int soundRefNum, boolean looping){// VARIABLES USED TO LOAD SOUND		int[] format= new int[1];        int[] size 	= new int[1];               int[] freq 	= new int[1];int[] loop 	= new int[1];ByteBuffer[] data = new ByteBuffer[1];if	( looping )	{	loop[0] = 1;	}else	{	loop[0] = 0;	}if 	( AL_INIT_OK )	{		if	( soundRefNum < MAX_SOUNDS )		{				ALut.alutLoadWAVFile			(			soundName, 			format, 			data, 			size, 			freq, 			loop			);				if	( ! ( myAL.alGetError() == AL.AL_NO_ERROR ) )			{			System.out.println("Error loading sound file '"+soundName+"'");			}					myAL.alBufferData			(			soundBuffers[soundRefNum],			format[0],			data[0],			size[0],			freq[0]			);		if	( ! ( myAL.alGetError() == AL.AL_NO_ERROR ) )			{			System.out.println("Error buffering sound file '"+soundName+"'");			}					ALut.alutUnloadWAV			(			format[0],			data[0],			size[0],			freq[0]			); 		if	( ! ( myAL.alGetError() == AL.AL_NO_ERROR ) )			{			System.out.println("Error unloading sound file '"+soundName+"'");			}	    	    	 	}	else		{					System.out.println("Invalid sound reference number '"+soundRefNum+"' maximum sound number="+(MAX_SOUNDS-1));				} 		}}static int getSoundChannelToPlay(){// FIND THE CHANNEL WHICH HAS BEEN USED LONGEST AGO// HOPEFULLY THIS WILL AVOID TWO SOUNDS TRYING TO PLAY ON SAME CHANNEL AT SAME TIMEint ChannelLongestAgo=0;for (int x = 0 ; x < MAX_SOURCES ; x++)	{		if	( (soundSourceLastMS[x] < soundSourceLastMS[ChannelLongestAgo]) && (!soundSourceLooping[x]) )		{				ChannelLongestAgo = x;				}		}return(ChannelLongestAgo);}}


As for MP3, its gonna be hard to find anything to get it loading since it is a closed format. Why not use Ogg Vorbis instead? I think there is a class set for Java which can read Ogg Vorbis files- 'JOggVorbis' i think....

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.