If you just want to play an audio, here's a way.
The audioFileDirectory
String variable needs the correct path to your audio file, otherwise an exception will be thrown and the program won't run.
Example of having the right audio file directory in a project if using an IDE:
- Make a folder inside
src
folder, e.g: "music" and put an audio file there
audioFileDirectory = "/music/name_of_audio_file";
The important part for an audio to play is that the main thread of the program needs somehow to be "alive", so the line
Thread.sleep(audio.getMicrosecondLength()/1000);
is where the main thread is "alive", and the argument audio.getMicrosecondLength()/1000
is the time that will be "alive", which is the whole length of the audio file.
public class AudioTest
{
void playAudio() throws Exception
{
String audioFileDirectory = "your_audioFileDirectory";
InputStream is = getClass().getResourceAsStream(audioFileDirectory);
BufferedInputStream bis = new BufferedInputStream(is);
AudioInputStream ais = AudioSystem.getAudioInputStream(bis);
Clip audio = AudioSystem.getClip();
audio.open(ais);
audio.loop(Clip.LOOP_CONTINUOUSLY);
audio.start();
Thread.sleep(audio.getMicrosecondLength()/1000);
audio.close();
} // end playAudio
public static void main(String[] args)
{
try
{
new AudioTest().playAudio();
}
catch (Exception e)
{
System.out.println("Class: " + e.getClass().getName());
System.out.println("\nMessage:\n" + e.getMessage() + "\n");
e.printStackTrace();
}
} // end main
} // end class AudioTest