Monday, April 22, 2013

Play sound program

This is a simple program to play sound files in Java. The program allows the user to choose the sound files and add them to the play list. The user can select one sound file to play from the play list or click the Play button to play the sound files starting from the first sound file to the last sound file in the list ( if the Stop button is not clicked). The package that is used to get the sound file played is javax.sound.sampled.

SoundPlayer source code:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.filechooser.*;
import javax.sound.sampled.*;

class  SoundInter extends JFrame implements ActionListener, ListSelectionListener{
            JFrame frame;
            JList playlist;
            JButton addbt;
            JButton playbt;
            DefaultListModel listmodel;
            JLabel lbllist;
            JScrollPane scr;
            JPanel panel;
            SoundControl sc;
            Clip clip;

1                      setTitle("Sound Player");
2                      setSize(300,450);
3                      setResizable(false);
4                      setDefaultCloseOperation(EXIT_ON_CLOSE);            
5                      Container cont=getContentPane();
6                      cont.setLayout(null);
7                      listmodel=new DefaultListModel();
8                      addbt=new JButton("Add to play list...");
9                      addbt.addActionListener(this);
10                    addbt.setBounds(10,350, 150, 30);
11                    playbt=new JButton("Play");
12                    playbt.addActionListener(this);
13                    playbt.setBounds(165,350, 110, 30);
14                    lbllist=new JLabel("Play List");
15                    lbllist.setBounds(10,3,300,30);
16                    lbllist.setForeground(Color.BLUE);
17                    playlist=new JList(listmodel);  
18                    playlist.setVisibleRowCount(20);
19                    playlist.setFixedCellWidth(250);
20                    playlist.addListSelectionListener(this);
21                    panel=new JPanel();
22                    panel.setBounds(10,33,270,300);
23                    scr=new JScrollPane(playlist);
24                    panel.add(scr);        
25                    cont.add(panel);
26                    cont.add(addbt);
27                    cont.add(playbt);
28                    cont.add(lbllist);                   
29                    setVisible(true);

30 public void actionPerformed(ActionEvent e){
            if(e.getSource()==addbt) showFileDialog(frame);
            else if(e.getSource()==playbt) {
                                    sc=new SoundControl();   
                                    showPlayFile("Play List");

31 public void valueChanged(ListSelectionEvent e){

32 public void playSound(String filename){
               AudioInputStream soundStream = AudioSystem.getAudioInputStream(new File(filename));
                AudioFormat soundFormat= soundStream.getFormat();
                DataLine.Info dl = new DataLine.Info(Clip.class, soundFormat);
                clip = (Clip)AudioSystem.getLine(dl);
               }catch(Exception ex){System.out.println("Sound loading error...");}
33 public void stopSound(){
                  }catch(Exception ex){}


34 public void showPlayFile(String filename){

35 public void showFileDialog(Frame frame){
            JFileChooser chooser = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter("WAV sound files", "WAV");
            int returnVal = chooser.showOpenDialog(frame);
             if(returnVal == JFileChooser.APPROVE_OPTION) {
                                    for(File imgfile: chooser.getSelectedFiles()){     

36 class SoundControl extends Thread{
            boolean started;

            public void run(){
                        int i;
                                                            if(i==listmodel.size()-1) i=-1; //replay
                        }catch(InterruptedException ie){System.out.println("Interrupted slide show...");}

            public void stopIt(){


37 public class SoundPlayer{
            public static void main(String args[]){
                        new SoundInter();


Play sound program in Java

Code Explanation:

1 Set the tile of the program window (Sound Player).
2 Specify the width and height of the program window when it opens.
3 Disable window resize.
4 Let the program window close when the user clicks the close button.
5 Create a container object to act as the controls placeholder.
6 Set container layout to null so that you can place controls in any locations with setBounds method.
7 A listmodel object is created. It is wrapped in JList. It has a methods to add to and remove elements from the JList.
8 Create a button object addbt. This button object is clicked to add sound files to the play list. 
9 Register the action event with the button object addbt so that it is able to react when the user clicks it.
10 Specify the location (left, top), and size (width, height) of the addbt button to display on the program window.
11 Create a button object playbt. This button object is clicked to play the selected sound file from the play list. 
12 Register the action event with the button object  playbt so that it is able to react when the user clicks it.
13 Specify the location (left, top), and size (width, height) of the playbt button to display on the program window.
14 Create a label object lbllist to display "Play List" or the current playing sound file text.
15 Define the location (left, top), and size (width, height) of the label to display on the window.
16 Set the text color on the lbllist label to the blue color.
17 Create the JList playlist object. The listmodel object is wrapped in the JList playlist object.
18 Define the number of rows (without scrolling) that can be visible in the playlist object.
19 Set the fixed width of the playlist cell so that it does not resize automatically. 
20 Add list selection listener to the playlist object object so that it is able to react when the user selects its element.
21 Create JPanel panel object to contain the playlist object. 
22 Define the location (left, top), and size (width, height) of the panel object.
23 Create JScrollPane src object to make the list box scrollable.
24 Add the src object to th panel object.
25 Add panel object to the container.
26 Add the button addbt object to the container.
27 Add the button playbt object to the container.
28 Add the label lbllist object to the container.
29 Make sure the program widow is visible. 
30 The actionPerformed method is rewritten to allow the addbt or playbt button to perform its task when it is clicked. This method is in the ActionListener interface. The getSource method the ActionEvent class is used to determine which button is clicked. If the user clicks the addbt button (e.getSource()==addbt) a file dialo is open to allow the user to choose the sound files. If the playbt is clicked, the start method of the SoundControl class is invoked to play the sound file. This button only is clicked to play the sound but also to stop the sound by invoking the stopIt method of the SoundControl class.
31 The playSound method is called to play the selected sound file when the user makes a list selection.
32 The code of the playSound method is defined here. To play a sound file in Java, firstly you create an AudioInputStream object to take the sound file. The AudioForm object can be got from the AudioInputStream object by invoking the its getFormat method. You have to create a DataLine object that takes two arguments: Clip.class and the AudioFormat object. The DataLine object is used for the output of the audio by means of the Clip. Then the Clip object used to play the sound can be obtained by invoking the getLine(DataLine) method of the AudioSystem class. Now you can play the sound by invoking the open(AudioInputStream) method followed by the start() method of the Clip object.
33 The stopSound method invokes the stop() method of the Clip oject to stop playing the sound the the user clicks the playbt (labeled Stop) button.
34 The showPlayFile method has code to display the current playing sound file on the lable lbllist.
35 The showFileDialog is implemented to show the file dialog in which the user can choose sound files to add to the playlist. This method is invoked when the user clicks the Add to Play List... button.
36 The SoundControl extends the Thread class. This class has the run method (automatically invoked when the its start method is invoked) to invoke the playSound method to play the selected sound file. It also has the stopIt() method to stop playing the sound file by invoking the stopSound method.
37 SoundPlayer class has the main method to start the program.

Note: In this program, we use the Clip object to play sound. From the javax.sound.sampled package, 
you have two choices to play the sound file. One is the use of the Clip object and another one is the use of the SourceDataLine object. For a short sound file, it is OK to use the Clip object. However, for a long sound file, you should use the SourceDataLine.  To play the sound file by using the SourceDataLine object, the following code may help you:
  AudioInputStream soundStream = AudioSystem.getAudioInputStream(new File(soundfile));
AudioFormat soundFormat= soundStream.getFormat();      
SourceDataLine line;
DataLine.Info info = new DataLine.Info(SourceDataLine.class, soundFormat);
    line = (SourceDataLine) AudioSystem.getLine(info);;
    int len= 0;
             byte[] sounData= new byte[102400];
             while (len != -1) {
                len=, 0, sounData.length);
                if (len>= 0) {
                line.write(sounData, 0, len);


  1. We're a bunch of volunteers and opening a brand new scheme in our community. Your website provided us with useful information to paintings on. You've done an impressive job and our entire neighborhood will likely be thankful to you. company secretary services in Singapore

  2. I haven’t checked in here for a while as I thought it was getting boring, but the last few posts are great quality so I guess I will add you back to my everyday bloglist. You deserve it my friend :)
    stunning website design

  3. Today, while I was at work, my sister stole my iPad and tested to see if it can survive a forty foot drop, just so she can be a youtube sensation. My iPad is now destroyed and she has 83 views. I know this is entirely off topic but I had to share it with someone! agv forklifts