The question basically explains itself. I want to take an audio file (I can use any format really) and have Java output sound from it when called on.
Asked
Active
Viewed 7,828 times
1 Answers
3
I think that this is an efficient way to have sound, whether you want to infinitely loop music or just want a sound to play once. I'm posting because it took me a long time to figure out which method of sound actually worked for my purposes. This method can only use AIFC, AIFF, AU, SND, and WAVE files. I find that the WAVE files, .wav, are easier because there are plenty of mp3(or whatever file you want to convert) to .wav converters online.
Imports:
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
Sound method:
public void sound() {
try {
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(this.getClass().getResource("NameOfFile.wav"));
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
// If you want the sound to loop infinitely, then put: clip.loop(Clip.LOOP_CONTINUOUSLY);
// If you want to stop the sound, then use clip.stop();
} catch (Exception ex) {
ex.printStackTrace();
}
}
I hope that this helps.

Anonymous
- 179
- 12