Basic audio output
suggest changeA minimal example that plays a sound file from local disk or from a URL looks like this. It works for uncompressed .wav files. The default Java Sound providers do not play MP3 or other compressed formats. clip.start() returns immediately, and this main method then returns, so the JVM can exit before the clip finishes unless you block (for example with clip.drain()).
import java.io.*;
import java.net.URL;
import javax.sound.sampled.*;
public class SoundClipTest {
// Constructor
public SoundClipTest() {
try {
// Open an audio input stream.
File soundFile = new File("/usr/share/sounds/alsa/Front_Center.wav"); //you could also get the sound file with an URL
AudioInputStream audioIn = AudioSystem.getAudioInputStream(soundFile);
AudioFormat format = audioIn.getFormat();
// Get a sound clip resource.
DataLine.Info info = new DataLine.Info(Clip.class, format);
Clip clip = (Clip)AudioSystem.getLine(info);
// Open audio clip and load samples from the audio input stream.
clip.open(audioIn);
clip.start();
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new SoundClipTest();
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents