The clip class has a loop and a stop method. But after you call stop the clip will get closed automatically so don’t call start or loop on it after you stopped it.
For a machine gun effect you need a delay. You probably have to create another Thread for that. You can communicate with that Thread through a volatile variable.
EDIT:
I updated my AudioData class
public class AudioData {
private byte[] data;
private AudioFormat format;
private volatile boolean machineGunActive = false;
private HashSet<Clip> clipsPlaying = new HashSet<>();
private synchronized void removeClip(Clip clip) {
clipsPlaying.remove(clip);
}
private synchronized void addClip(Clip clip) {
clipsPlaying.add(clip);
}
private synchronized void stopAllClips() {
for(Clip clip: clipsPlaying) clip.stop();
clipsPlaying.clear();
}
AudioData(String fileName) {
try {
AudioInputStream sounds = AudioSystem.getAudioInputStream(AudioData.class.getResource(fileName));
format = sounds.getFormat();
int size = sounds.available();
data = new byte[size];
sounds.read(data);
sounds.close();
} catch(Exception e) {
e.printStackTrace();
}
}
public Clip createClip() {
try {
final Clip clip = AudioSystem.getClip();
clip.addLineListener(new LineListener() {
public void update(LineEvent e) {
LineEvent.Type type = e.getType();
if(type == type.STOP) {
clip.close();
removeClip(clip);
}
}
});
clip.open(format, data, 0, data.length);
return clip;
} catch(Exception e){
e.printStackTrace();
}
return null;
}
public void play() {
Clip clip = createClip();
addClip(clip);
clip.start();
}
public void loop(int n) {
Clip clip = createClip();
addClip(clip);
clip.loop(n);
}
public void loopForever() {
Clip clip = createClip();
addClip(clip);
clip.loop(Clip.LOOP_CONTINUOUSLY);
}
public void stop() {
machineGunActive = false;
stopAllClips();
}
public void stopMachineGun() {
machineGunActive = false;
}
public void playMachineGun(final int delay) {
machineGunActive = true;
new Thread() {
public void run() {
while(machineGunActive) {
play();
try {
Thread.sleep(delay);
} catch(Exception e) {
e.printStackTrace();
}
}
}
}.start();
}
}
Try this
AudioData data = new AudioData("shoot.wav");
data.playMachineGun(100);
Thread.sleep(2000);
data.stopMachineGun();
The difference between stop() and stopMachineGun() is that stop() will stop playing immediately, while stopMachineGun() allows the sound to fade out naturally.