Reputation: 5106
I'm trying to play a sound over and over. I have this code:
public void play() {
try {
URL defaultSound = getClass().getResource(filename);
AudioInputStream audioInputStream =
AudioSystem.getAudioInputStream(defaultSound);
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start( );
System.out.println(clip.getMicrosecondLength());
Thread.sleep(clip.getMicrosecondLength() / 1000);
clip.addLineListener(new LineListener() {
@Override
public void update(LineEvent event) {
try {
clip.start();
Thread.sleep(clip.getMicrosecondLength() / 1000);
}
catch (Exception e) {
e.printStackTrace();
}
}
});
}
catch (Exception e) {
e.printStackTrace();
}
}
but it only plays the sound once.
Upvotes: 0
Views: 235
Reputation: 168825
clip.open(audioInputStream);
clip.start( );
Should be:
clip.open(audioInputStream);
clip.loop(Clip.LOOP_CONTINUOUSLY); // <- NEW!
clip.start( );
See Clip.loop(int)
:
Parameters:
count
- the number of times playback should loop back from the loop's end position to the loop's start position, orLOOP_CONTINUOUSLY
to indicate that looping should continue until interrupted
Upvotes: 1
Reputation: 5246
You're going to want to likely set the Clip's frame position
using Clip#setFramePosition to 0. You will want to call this before Clip#start
. You also need to check if the LineEvent
type is the value LineEvent.Type#STOP to ensure the event is an update event or close, and it is indeed when it stops.
@Override
public void update(LineEvent event) {
try {
if (event.getType() == LineEvent.Type.STOP) {
clip.setFramePosition(0);
clip.start();
Thread.sleep(clip.getMicrosecondLength() / 1000);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
Upvotes: 0