Reputation: 539
I am making a 2d RPG game and i was wanting to get background music working. I wrote a sound class that plays the music on a separate thread but i cannot figure out how to make it loop. My Sound class is as follows:
package tileRPG.gfx;
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
public class Sound implements Runnable
{
private String fileLocation = "res/bgMusic.wav";
public Sound() { }
public void play()
{
Thread t = new Thread(this);
t.start();
}
public void run()
{
playSound(fileLocation);
}
private void playSound(String fileName)
{
File soundFile = new File(fileName);
AudioInputStream audioInputStream = null;
try
{
audioInputStream = AudioSystem.getAudioInputStream(soundFile);
}
catch (Exception e)
{
e.printStackTrace();
}
AudioFormat audioFormat = audioInputStream.getFormat();
SourceDataLine line = null;
DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
try
{
line = (SourceDataLine) AudioSystem.getLine(info);
line.open(audioFormat);
}
catch (LineUnavailableException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
line.start();
int nBytesRead = 0;
byte[] abData = new byte[128000];
while (nBytesRead != -1)
{
try
{
nBytesRead = audioInputStream.read(abData, 0, abData.length);
}
catch (IOException e)
{
e.printStackTrace();
}
if (nBytesRead >= 0)
{
int nBytesWritten = line.write(abData, 0, nBytesRead);
}
}
line.drain();
line.close();
}
}
Upvotes: 0
Views: 5114
Reputation: 5565
public void run ()
{
while(true)
{
playSound(fileLocation);
}
}
This creates an infinite loop. Adjust accordingly.
When you start a thread, it will execute any code that is in the run()
method and then exit. So this is where the loop would go in order to repeatedly play the sound (without blocking your other threads/code).
This solution has no way of stopping this thread (and therefore stopping playback) with your current code, but I assume you are writing this in stages. The thread will stop playback and exit when the application does currently.
Upvotes: 2
Reputation: 46841
Use recursion
Sample code:
private void playSound(String fileName)
{
...
line.drain();
line.close();
//recursive call to same method
playSound(fileName);
}
You can make it more better by moving static part of the method playSound()
in run()
method. In that case you don't need to read the file again.
Hint: pass SourceDataLine
in playSound()
method instead of fileName
.
Upvotes: 0