Roshana Pitigala
Roshana Pitigala

Reputation: 8806

Play audio files in Java

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.

Upvotes: 0

Views: 2766

Answers (2)

user7619949
user7619949

Reputation:

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
}

Upvotes: 0

wero
wero

Reputation: 33000

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.

Upvotes: 2

Related Questions