Reputation: 317
I am developing an alarm clock program that plays an audio clip as an alarm. I can successfully play an audio clip, and terminate an inactive alarm. However, when I try to terminate an alarm that is currently playing, the audio keeps playing. Solutions I've tried were setting the clip to null, clip.stop(); and
public void stopSound(Clip clip){
clip.stop();
clip.flush();
clip.close();
}
Is there a way to end a clip at any percentage through a clip?
Upvotes: 1
Views: 60
Reputation: 67
This works for me. It stops after 5 seconds of playing.
import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
public class Main {
public static void main(String[] args) {
playMusic("<Type your path to music here>");
}
static void playMusic(String musicLocation) {
new Thread(() -> {
try {
File musicPath = new File(musicLocation);
if (musicPath.exists()) {
AudioInputStream audioInput = AudioSystem.getAudioInputStream(musicPath);
Clip clip = AudioSystem.getClip();
clip.open(audioInput);
clip.start();
TimeUnit.SECONDS.sleep(5);
clip.stop();
} else {
System.out.println("Can't find file");
}
} catch (IOException | UnsupportedAudioFileException | LineUnavailableException | InterruptedException e) {
throw new RuntimeException(e);
}
}).start();
}
}
Upvotes: 1