java play sound file code example

Example 1: How to play sounds on java

void playSound(String soundFile) {
    File f = new File("./" + soundFile);
    AudioInputStream audioIn = AudioSystem.getAudioInputStream(f.toURI().toURL());  
    Clip clip = AudioSystem.getClip();
    clip.open(audioIn);
    clip.start();
}

Example 2: how to play an audio in java

AudioInputStream input = new AudioInputStream(Path_to_the_file);
Clip clip=AudioSystem.geClip();
clip.open(input);
Clip.loop(Clip.LOOP_CONTINUOSLY);
clip.start();

Example 3: how to play a clip of audio in java when needed

Clip clip;

try {
	AudioInputStream input=AudioSystem.getAudioInputStream(new File("audio.wav"));
	clip=AudioSystem.getClip();
	clip.open(input);
	clip.start();
} catch (UnsupportedAudioFileException e) {
	e.printStackTrace();
} catch (IOException e) {
	e.printStackTrace();
} catch (LineUnavailableException e) {
	e.printStackTrace();
}

Example 4: how to play an audio file in java

import java.applet.*;
AudioClip ac = getAudioClip(getCodeBase(), soundFile);
ac.play();   //play once
ac.stop();   //stop playing
ac.loop();   //play continuously