Simple Music Player In Java

In This Tutorial, we will learn to create a simple music player in Java. The music player in which we can start a song, pause a song and restart a song. We will use swings ie. JButton, JFrame for this task. We can create the music player using any IDE ie. Notepad, Notepad++, Eclipse, Netbeans, etc.

In our case, we will use Netbeans IDE as Netbeans is one of the most used IDE in the case of Java programs as Netbeans create most of the code for us. Very few Efforts of user are required while working with any java project using Netbeans.

Java Program to create a simple music player

First of all, we need to create a new project from the file menu. Then in the project, we will create a package.

We use packages so that we can use methods and constructors of any class within the same package without any problem. After creating a package we will create a new class under the package. And then we will import all the Required predefined packages. In this Project we require

  • io. File
  • io.IOException
  • javax.media.*
  • net.URL

All these packages are used in the project. We can easily import all the packages Except javax.media.

IOException package helps us to check Exceptions that are caused due to Input or Output operation.

The exception may disturb the normal flow of the program. So to avoid exceptions we usually handle Exceptions.

Also, read: Hospital Management System using core Java

 

JMF-JAVA MEDIA FRAMEWORK

Before importing javax.media we need to download JMF ie. java media framework. There are various options for JMF but we require download cross-platform.

Here is the link to download JMF.

https://www.oracle.com/java/technologies/java-archive-downloads-java-client-downloads.html#7372-jmf-2.1.1e-oth-JPR

After downloading cross-platform JMF, we need to extract the files, After extracting files we will open the folder and need to click on the lib folder, from the lib folder we need to select the jmf.jar file.

Now we will use this jmf.jar file in the project we are working on. To add this file to the NetBeans project we need right-click on the Library folder, we will receive 3 options

  • Add  jar
  • project
  • library

from these options, we will select the Add jar option. After selecting this option we can select the file that we require. In this project, we require a jmf.jar file.

package javaapplication26;
import java.io.File;
import java.io.IOException;
import javax.media.*;
import java.net.URL;

public class MediaPlayer extends javax.swing.JFrame {
 Player ap=null;
 String ap1=" ";
 String ap3=" ";
  
    public MediaPlayer() {
        initComponents();
        ap1=("C:\\Users\\lenovo\\Downloads\\Chitta Kurta Original - Karan Aujla  Gurlez Akhtar (DJJOhAL.Com).wav");
       ap3="C:\\Users\\lenovo\\Downloads\\Dhakka - Sidhu Moose Wala (DjPunjab.Com).wav";
         
        
    }
    private void initMediaPlayer(String path){
        try{
            URL url=new File(path).toURL();
            ap=Manager.createRealizedPlayer(url);
        }catch(Exception e){
         
            
        }
    }

    @SuppressWarnings("unchecked")
                             
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        playButton = new javax.swing.JButton();
        pauseButton = new javax.swing.JButton();
        stopButton = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        playButton.setText("play");
        playButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                playButtonActionPerformed(evt);
            }
        });

        pauseButton.setText("pause");
        pauseButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pauseButtonActionPerformed(evt);
            }
        });

        stopButton.setText("stop");
        stopButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                stopButtonActionPerformed(evt);
            }
        });

        jButton1.setText("karan");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("sidhu moosewala");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(110, 110, 110)
                        .addComponent(jLabel1))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(21, 21, 21)
                        .addComponent(playButton)
                        .addGap(18, 18, 18)
                        .addComponent(pauseButton)
                        .addGap(29, 29, 29)
                        .addComponent(stopButton)))
                .addGap(0, 0, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(178, 178, 178))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(112, 112, 112)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton2)
                    .addComponent(jButton1))
                .addContainerGap(133, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(12, 12, 12)
                .addComponent(jLabel2)
                .addGap(18, 18, 18)
                .addComponent(jLabel1)
                .addGap(26, 26, 26)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(playButton)
                    .addComponent(pauseButton)
                    .addComponent(stopButton))
                .addGap(33, 33, 33)
                .addComponent(jButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton2)
                .addContainerGap(108, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }                      
   

    private void playButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
       ap.start();
       
    }                                          

    private void pauseButtonActionPerformed(java.awt.event.ActionEvent evt) {                                            
        ap.stop();
        ap.setMediaTime(new Time(0.0));
    }                                           

    private void stopButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
        ap.stop();
    }                                          

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        initMediaPlayer(ap1);
    }                                        

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        initMediaPlayer(ap3);
    }                                        

    public static void main(String args[]) {
     
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MediaPlayer().setVisible(true);
            }
        });
    }

                        
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JButton pauseButton;
    private javax.swing.JButton playButton;
    private javax.swing.JButton stopButton;
                      
}

 

About project

In this project, MediaPlayer is the name of the class. We are extending JFrame because we will use JFrame and JButton etc for creating the front-end of the media player. Using NetBeans we can easily drag and drop the required fields  Netbeans will automatically generate the code for us.

In the above code, we will create a constructor and in the constructor, we are using the initComponent() method which is autogenerated when we use Netbeans. The initComponent() method consists of the code for setting the layout of the front-end. There are several different types of layouts that we example

  • GridLayout
  • GridbagLayout
  • CardLayout
  • FlowLayout
  • box layout
  • GroupLayout, etc

Flow Layout is the default layout for java programs.

The initComponent() method also consists of the code which we can use to change the name of buttons, panels, etc.(ie. swings which we are using in our project). By default jButton1, jButton2 are the names of buttons that we add to our frame. In the above code playButton, pauseButton and stopbutton are the names of buttons ie. start button, pause button and stop button.

We changed the names of the button from

  • JButton1 to playButton
  • JButton2 to pauseButton
  • JButton3 to stopButton

The internal part of the project

In the code above ap1  and ap3 are the instance variables that store the location of any song. The instance variable is the variable which we can use in any method of the entire class. This is not in case of a local variable, as the local variable is declared inside a method and its scope resides only in the method in which we are declaring the variable.

We use

  • toURL() method for representing the equivalent file URL.
  • createRealizedPlayer() method to create a player to play the media specified in the URL.
  • playButtonActionPerformed(),pauseButtonActionPerformed(),stopButtonActioPerformed () to define the functionalities of the buttons we are using  ie start() and stop().

How to run the project?

We are using buttons on the front end to choose the song. First, we need to select the name of the song, after selecting the name we can press the play button to play the song.

We are using buttons to select the song. Further, we are using these methods to assign a particular song to the player.

How songs are assigned?

We need variables to store location of the songs . In the above code ap1 and ap2 are the variables that we use to store the location.

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
initMediaPlayer(ap1);
}

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
initMediaPlayer(ap3);
}

After this main() method is again autogenerated by the Netbeans.

Below is the picture where you can see how our simple music player looks:

Java Music Player

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *