0

I am trying to play a simple audio file which is in the same directory near the class file. I tried many examples from the internet, but all the others gave me errors which I couldn't even understand.

Then I found this, and I am using it now.

There are neither compile errors nor runtime errors. But the problem is I cannot hear any noise.

import java.io.File;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;

class A{
    public static void main (String[]args){
        try {
                AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("abc.wav").getAbsoluteFile());
                Clip clip = AudioSystem.getClip();
                clip.open(audioInputStream);
                clip.start();
            } catch(Exception ex) {
                System.out.println("Error with playing sound.");
            }
    }
}

screen-shot

Please note that my system volume is 80%, and the audio file plays in VLC media player.

Roshana Pitigala
  • 8,437
  • 8
  • 49
  • 80

2 Answers2

2

Starting the audio clip does not block the main method. So

 clip.start();

starts playing and then returns. Now your main method ends and therefore the Java process ends. No sound.

If you do

 clip.start();
 Thread.sleep(20000);

you should hear the clip playing for 20 seconds.

So for a working program just must make sure that the main thread does not end as long as you want to play the clip.

wero
  • 32,544
  • 3
  • 59
  • 84
0

Hold the thread for a while until the audio clip plays.

long audioPlayTime = 1000; //clip duration in miliseconds.
try {
           Thread.sleep(audioPlayTime);
} catch (InterruptedException ex){
            //TODO
}