public static void main(String[] args) {
File Song = null;
boolean flag = true;
while(flag) {
System.out.println("Enter number to play song: ");
System.out.println("Enter 0 to close: ");
Scanner input = new Scanner(System.in);
int c = input.nextInt();
switch(c) {
case 1:
Song = new File("C:\\Users\\Majd\\eclipse-workspace\\Audio\\s1.wav");
PlaySound(Song);
break;
case 2:
Song = new File("C:\\Users\\Majd\\eclipse-workspace\\Audio\\s2.wav");
PlaySound(Song);
break;
case 3:
Song = new File("C:\\Users\\Majd\\eclipse-workspace\\Audio\\s3.wav");
PlaySound(Song);
break;
case 4:
Song = new File("C:\\Users\\Majd\\eclipse-workspace\\Audio\\Guitar.wav");
PlaySound(Song);
break;
case 0:
flag = false; break;
}
}
}
public static void PlaySound(File Sound) {
try {
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(Sound));
clip.start();
Thread.sleep(clip.getMicrosecondLength()/100);
}catch(Exception e) {
System.err.println(e.getMessage());
}
}
Of course it does. You’ve got an infinite loop there that’s always executing. You need a way to react to input when you get it, otherwise the loop will run at the maximum available speed. (Or you could just do a sleep() call, if that works for you).
Two things: This isn’t a general Java support forum.
And I won’t write your code for you. If you don’t even know where to place that sleep call, then you might want to learn a bit more Java. There’s plenty of good resources on the net.
it’s not the loop’s fault the loop is fine, what you are doing wrong is that you are initialising the song every time you need it, init all the songs first then play the one you need.