Get up to 80 % extra points for free! More info:

Playing sounds (wav files) in Java

In today's tutorial, we're going to show you how to play wav audio file in Java easily. Since it's very simple, we'll also show how to make a simple wave player.

All we're going to need is a Music class, into which we'll import the necessary libraries and prepare a constructor with one parameter. The parameter will be String and will indicate the path to our file. We'll also use a MyJFrame class, which will run everything through the main() method.

First, let’s take a look at the Music class:

import java.net.MalformedURLException;
import java.net.URL;
import java.applet.*;

public class Music {

    private URL file;

    public Music(String path) {
       try {
            file = new URL("file:" + path);
        } catch (MalformedURLException ex) {
            System.err.println(ex);
        }
        Applet.newAudioClip(file).play();
    }

}

And what do these imports actually do? Well the first one is used to catch MalformedURLException. The second import is for the file path and in the third package we import the applet class and its methods.

We also created a private URL attribute to which we assign the file path we get from the constructor's parameter. Of course, everything must be inside the try block and everything will be guarded by MalformedURLException. You see, it's pretty simple. Now, all we have to do is just to create a main class called MyJFrame, in which we'll run everything via the main() method:

public class MyJFrame
{
    public static void main(String args[]) {
        Music music = new Music("song.wav");
    }
}

In the MyJFrame class I used the song.wav file which can be found in the source code attached with other wav files.

The Wave player

Now, as promised, we'll make a simple program to play wav files the user selects. First of all, we'll rewrite the MyJFrame class completely. Remove everything you have in it and replace it with the basic layout shown below:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;

public class MyJFrame extends JFrame
{
    public JButton play, choose;
    private String file;
    public static MyJFrame instance;

    public MyJFrame()
    {
      this.setSize(400,400);
      this.setTitle("Wave audio player");
      this.setComponents();
      this.setListeners();
    }

    public void setComponents(){

    }

    public void setListeners(){

    }

    public static Frame setup(){
      MyJFrame window = new MyJFrame();
      window.setVisible(true);
      window.setLocationRelativeTo(null);
      return window;
    }

    public static void main(String args[]){
      MyJFrame.setup();
    }

}

First we import the necessary packages. Then we set the size and title in the constructor and call the necessary methods. Then we create a static method of the Frame type in which the basic window properties are set. Finally, there's the main() method, which runs it all.

Now let's implement the setComponents() method:

Container pane = this.getContentPane();
pane.setLayout(new FlowLayout());
pane.setBackground(Color.PINK);
this.choose = new JButton("choose");
this.play = new JButton("play");
pane.add(choose);
pane.add(play);

The method does nothing extraordinary. We save the panel to the container, set the FlowLayout to it and add two buttons. The form should look like this:

Player - Files and I/O in Java

Now it's the time for the setListeners() method, which is going to be a little more interesting:

this.choose.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e){
        FileDialog fd = new FileDialog(instance);
        fd.setMode(FileDialog.LOAD);
        fd.setVisible(true); // makes the window visible
        String newFile = fd.getDirectory() + fd.getFile(); // returns the folder path + the file path
        if (newFile != null){
            file = newFile;
        }
    }
});

this.play.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        Music m = new Music(file);  // file = absolute path to the file retrieved from the file variable
    }
});

In the method, we set action listeners for the choose and play buttons. Once the choose button is pressed a FileDialog box will pop up.

Window - Files and I/O in Java

There we can select a file thanks to the property set by fd.setMode(FileDialog.LOAD). Then we save the file path to the file variable. We let our file variable refer to the newFile variable.

Once we press the play button, an instance of the Music class is created and the file is played. So the file is completely done.

Here is the whole MyJFrame class as it should look like now:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;

public class MyJFrame extends JFrame {

    public JButton play, choose;
    private String file;
    public static MyJFrame instance;

    public MyJFrame() {
        this.setSize(400, 400);
        this.setTitle("Wave audio player");
        this.setComponents();
        this.setListeners();
    }

    public void setComponents() {
        Container pane = this.getContentPane();
        pane.setLayout(new FlowLayout());
        pane.setBackground(Color.PINK);
        this.choose = new JButton("choose");
        this.play = new JButton("play");
        pane.add(choose);
        pane.add(play);
    }

    public void setListeners() {
        this.choose.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                FileDialog fd = new FileDialog(instance);
                fd.setMode(FileDialog.LOAD);
                fd.setVisible(true);
                String soubor = fd.getDirectory() + fd.getFile();
                if (soubor != null) {
                    file = soubor;
                }
            }
        });

        this.play.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Music m = new Music(file);
            }
        });
    }

    public static Frame setup() {
        MyJFrame window = new MyJFrame();
        window.setVisible(true);
        window.setLocationRelativeTo(null);
        return window;
    }

    public static void main(String args[]) {
        MyJFrame.setup();
    }
}

If anyone still wouldn't understand any part of the code, then download the file attached to this article, where you will find wav files to play.


 

Download

By downloading the following file, you agree to the license terms

Downloaded 36x (16.69 MB)
Application includes source codes in language Java

 

Previous article
Java - Writing/reading data types to/from Windows registry
All articles in this section
Files and I/O in Java
Article has been written for you by David Capka Hartinger
Avatar
User rating:
No one has rated this quite yet, be the first one!
The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
Unicorn university David learned IT at the Unicorn University - a prestigious college providing education on IT and economics.
Activities