Robo Home | Changes | Preferences | AllPages

Playing Sounds from a robot

I posted this on the Yahoo! Group and Pez suggested I post it here as well: How to play sounds with your robot:

First of all, the complications associated with doing this: --sometimes it's touchy - if you do it exactly like I have here and don't try to play a sound right as the round ends (a second or two before is generally ok, that's what I use it for). The main problem is that sometimes there are threads that don't end before the round does. --The sound clip must be one that is natively recognized by the Java Sound API (.wav files, and maybe 4 others work), otherwise, you may have to do quite a bit more than this. --The sound clip must be in the data directory for this robot - this means two things: first, it must be an AdvancedRobot. Second, the sound clip must be smaller than the maximum directory size for that robot (I think).

Feel free to copy this code into any robot you would like to add sound clips to:

import javax.sound.sampled.*;

public void playSound(String filename)
		AudioInputStream in = AudioSystem.getAudioInputStream(getDataFile(filename));
		DataLine.Info info = new DataLine.Info(Clip.class, in.getFormat(), ((int)in.getFrameLength()*in.getFormat().getFrameSize()));
		Clip clip = (Clip) AudioSystem.getLine(info);
	catch (Exception e)
		System.out.println("Exception playing sound:");
If you absolutely felt like you 'needed' to play a larger sound file than you can put in your directory (Is it like 20k you can store for each robot?), you could try putting the clip in a zip file and doing something like this (filename is now the name of the zip file, I'm assuming there is only one sound clip in the zip file, or that the one you want is the first entry in the zip file):
ZipInputStream zipin = new ZipInputStream(new FileInputStream(getDataFile(filename)));
AudioInputStream in = AudioSystem.getAudioInputStream(zipin);
DataLine.Info info = new DataLine.Info(Clip.class, in.getFormat(), ((int)in.getFrameLength()*in.getFormat().getFrameSize()));

The sound version of SpareParts 0.7.6 uses the zipped sounds as above, except that it accesses all sounds from the same zip file. The zipin.getNextEntry?() part actually returns a ZipEntry? object, and if its getName() function returns the filename desired, that's the one I stay with and do the AudioInputStream? with. -- Kawigi

Robo Home | Changes | Preferences | AllPages
Edit text of this page | View other revisions
Last edited May 17, 2004 16:03 EST by PEZ (diff)