Hi, quite analogous to the static class that is being widely used to accelerate images in your gfx card, I also made a static class which plays sampled media sounds, like .wav files
All you have to do is put this class in your project tree, initialize all the sounds by calling this once anywhere: SoundHandler.get().loadSoundFx();
and whenever you need to play a sound just call: SoundHandler.get().play(“boom1”);
I am also pretty much a beginner, so I hope other beginners can make good use of this class too. If you have any questions or comments, reply to this thread, or email me at k.verbist@student.tudelft.nl
I am also interested in what the advanced programmers have to say about this class.
/*
- SoundHandler.java
- Created on May 6, 2006, 1:39 AM
- To change this template, choose Tools | Options and locate the template under
- the Source Creation and Management node. Right-click the template and choose
- Open. You can then make changes to the template in the Source Editor.
*/
package tankpwnage;
import java.util.HashMap;
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.*;
/**
*
-
@author Cyclonis Delta
*/
public class SoundHandler implements LineListener {private static final int BUFFER = 128000;
private static SoundHandler instance = new SoundHandler();
private HashMap soundFiles;
public static SoundHandler get() {
return instance;
}public void loadSoundFx() {
soundFiles = new HashMap();
File directory = new File("./sound/fx");
File[] files = directory.listFiles();
for (int i=0;i<files.length;i++) {
if (files[i].isFile()) {
// This is a sound effect
String filename = files[i].getName();
String path = “./sound/fx/”+filename;
File theFile = new File(path);
int dot = filename.indexOf(".wav");String ref = filename.substring(0, dot); AudioInputStream audioInputStream = null; Clip clip = null; try { audioInputStream = AudioSystem.getAudioInputStream(theFile); if (audioInputStream != null) { AudioFormat format = audioInputStream.getFormat(); DataLine.Info info = new DataLine.Info(Clip.class, format); try { clip = (Clip) AudioSystem.getLine(info); //clip.addLineListener(this); clip.open(audioInputStream); soundFiles.put(ref, clip); } catch (LineUnavailableException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } catch (Exception e) { e.printStackTrace(); } } }
}
public void update(LineEvent event)
{
if (event.getType().equals(LineEvent.Type.STOP))
{
Clip clip = (Clip)event.getLine();
clip.setFramePosition(1);
}
else if (event.getType().equals(LineEvent.Type.CLOSE))
{
/*
* There is a bug in the jdk1.3/1.4.
* It prevents correct termination of the VM.
* So we have to exit ourselves.
*/
System.exit(0);
}
}public void play(String ref) {
Clip clip = (Clip) soundFiles.get(ref); if (clip.isRunning()) { clip.stop(); clip.setFramePosition(1); } clip.addLineListener(this); //while (!clip.isRunning()) { clip.start(); //}
}
}