Playing Audio in Java

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, .ogg, .au, and .midi files, but not (unfortunately) .mp3 files, probably because of licensing issues.


Troubleshooting.png Having problems with this tutorial? Try the troubleshooting page!