- Last Updated on 29 September 2013
In this article, we would like to present a Swing-based application that is able to play back audio files (in WAV (*.wav) format) and show you how to build one. This audio player program will look like this:
The program is working just like a typical audio player. First, let’s see how this program is supposed to work. Click the Open button to pick an audio file:
Note that this audio player program is built based on pure Java Sound API so it can play only *.wav files (other supported formats are *.aifc, *.aiff, *.au and *.snd but these are less popular). Select a file in the dialog then click Open, the program will play back the audio file:
You can notice that duration of the audio file is shown on the right most (in form of hour:minute:second). The current playing time is shown on the left most. During the playback, the slider is moving gradually from the left to the right to indicate the progress. Click the Pause button to temporarily pause the playback:
The slider stops moving and the Pause button’s label becomes Resume which will continue the playback when clicked.
Click the Stop button to terminate playing the audio:
The slider moves to the beginning position and the Stop button becomes Play button which will start over the audio playback when clicked.
During the playback we can click the Open button to choose another audio file. In this case, the current playback will be stopped and start playing the newly chosen audio file.
Now let’s see how this pretty nice program is built. The following class diagram describes how the program is designed:
The program consists of three classes:
- AudioPlayer.java: this is a utility class that provides primary functionalities for playing back an audio file like play, stop, pause, and resume. It is based on the Java Sound API. This class is an enhanced version of the technique discussed in the tutorial: How to play back audio in Java with examples. The enhancements are for working in a Swing-based application. A separate thread should be spawned to use this utility class.
- PlayingTimer.java: this thread-based class is responsible to generate current playing time during the playback. It also updates the slider accordingly.
- SwingAudioPlayer.java: this is the main program which is based on a JFrame. It constructs the user interface and wires to AudioPlayer and PlayingTimer together to form a nice-looking and functional audio player program.
It’s not convenient for listing the entire program’s source code here. So you can study this program by downloading the below attachment which includes an executable jar file and full project’s source code. Enjoy!
Recommended Book: Core Java, Volume II--Advanced Features (9th Edition) (Core Series)