Introduction
Getting a Java program to play simple audio is very simple. This tutorial will look at how this is done.
How to Play Audio in Java
Below is the code for a simple program that loads an audio file that is specified on the command line and plays it.
import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import sun.audio.AudioPlayer; import sun.audio.AudioStream; public class AudioDemo { public static void main(String[] args) throws Exception { String filename = args[0]; InputStream in = new FileInputStream(new File(filename)); AudioStream audioStream = new AudioStream(in); AudioPlayer.player.start(audioStream); } }
In the first line of the program, we get the filename from the command line. The next line creates a new InputStream that reads directly from the file. In the next line, we wrap that InputStream in an AudioStream. Finally, we start playing the music by calling AudioPlayer.player.start();
Also, you will probably find it useful to be able to stop music that is already playing. To do this, you can call the AudioPlayer's stop() method with the appropriate AudioStream object as shown below:
AudioPlayer.player.stop(audioStream);
I didn't experiment too much, but from what I did, it appears that this will play .wav files, but not .mp3 files.
Conclusion
This tutorial showed how to play basic audio in Java. In the future, I would like to add more tutorials for Java, but for now I would recommend the Java Tutorials if you want more information about Java and playing audio in Java.


I think that it plays .ogg format files as well. It doesn't play mp3 because of licensing.
Post preview:
Close preview