Can someone please help me understand why this code below doesn't work?
I start the clip by calling method start()
. This method creates a new thread for the clip to run. However, no it doesn't seem to play anything.
The code is compiled without any error...
public class Audio
{
private Clip clip;
private Thread thread;
public Audio (String audioFile)
{
AudioInputStream audioStream = null;
URL audioURL = this.getClass().getClassLoader().getResource(audioFile);
// Obtain audio input stream from the audio file and load the information
// into main memory using the URL path retrieved from above.
try { audioStream = AudioSystem.getAudioInputStream(audioURL); }
catch (Exception e)
{
e.printStackTrace();
System.exit(1);
}
try
{
// Retrieve the object of class Clip from the Data Line.
this.clip = AudioSystem.getClip();
// Load the audio input stream into memory for future play-back.
this.clip.open(audioStream);
}
catch (LineUnavailableException e)
{
e.printStackTrace();
System.exit(1);
}
catch (IOException e)
{
e.printStackTrace();
System.exit(1);
}
}
public void start()
{
Runnable r = new Runnable() {
public void run()
{
loop();
}
};
thread = new Thread(r);
thread.start();
}
public void loop ()
{
// Rewind the media to the beginning of the clip.
this.clip.setFramePosition(0);
// Continuously play the clip.
this.clip.loop(Clip.LOOP_CONTINUOUSLY);
try
{
Thread.sleep(5000);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
UPDATE
I found the problem! The problem is because of the audio file. I used a different audio file and I can hear the sound with the code above.
It is just really annoying that the code compiled without any error or warning. I detected the problem by getting the audio format, then pass it to an object of class DataLine.Info. Then, retrieve the clip from the Data Line.
So, basically instead of getting the clip by:
this.clip = AudioSystem.getClip();
I would get the clip by:
AudioFormat format = audioStream.getFormat();
DataLine.Info info = new DataLine.Info(Clip.class, format);
this.clip = (Clip) AudioSystem.getLine(info);
When I compiled with this, Java threw below error:
No line matching interface Clip supporting format PCM_SIGNED 48000.0 Hz, 24 bit
So, I replaced the audio file, and it worked !