Hello guys,
i need help with playing sound effects in a game.
i have the following class for playing sound effects
SoundManager:
public class SoundManager implements Runnable
{
private int soundID;
public SoundManager(int soundID)
{
this.soundID = soundID;
}
@Override
public void run()
{
File file = new File (".\\Sounds\\sound" + soundID + ".wav");
AudioInputStream audioStream = null;
AudioFormat format = null;
SourceDataLine sourceLine = null;
int BUFFER_SIZE = 128000;
try {
audioStream = AudioSystem.getAudioInputStream(file);
} catch (UnsupportedAudioFileException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
format = audioStream.getFormat();
DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
try {
sourceLine = (SourceDataLine) AudioSystem.getLine(info);
sourceLine.open(format);
} catch (LineUnavailableException e) {
e.printStackTrace();
System.exit(1);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
sourceLine.start();
int nBytesRead = 0;
byte[] abData = new byte[BUFFER_SIZE];
while (nBytesRead != -1) {
try {
nBytesRead = audioStream.read(abData, 0, abData.length);
} catch (IOException e) {
e.printStackTrace();
}
if (nBytesRead >= 0) {
@SuppressWarnings("unused")
int nBytesWritten = sourceLine.write(abData, 0, nBytesRead);
}
}
sourceLine.drain();
sourceLine.close();
}
}
And when there is a collision, i create enw instance of the sound manager and call .run() method:
SoundManager soundManager = new SoundManager(1);
soundManager.run();
but this is blocking the game rendering until the sound is played, i thought running a seperate thread for sound, fixes the problem but it did not.
What can i do for sounds not to block the game ?