Playing MP3 Audio using JAVA

In this post we’ll discuss about playing music files using java . cool huh ? Well, this post contains three ways to play music files.To play files with au or wav extensions we’ll use libraries already available with JDK.For MP3 files there is use of an external API called JLayer(Javazoom project). Ok .. let’s get started. package 
 Import following to your class :


Following is the sample code :

           try {
              InputStream in = new FileInputStream(MusicFileName.wav); //InputStream for the audio file
              AudioStream  as = new AudioStream(in); // AudioStream object using InputStream of audio file
              //Following is to continuously play audio until it is not stopped
              AudioData data = as.getData(); 
              ContinuousAudioDataStream  cas = new ContinuousAudioDataStream (data);
     (cas); // To play continuously
              AudioPlayer.player.stop (cas); // To stop 
           }catch (Exception ex){
             System.out.println(“Exception while playing audio “+ex.getMessage());

To play the audio without loop following can be used

To stop following :


2. java.applet package

import following

import java.applet.*;

Sample code :
//key.mp3 bundled with the JAR file

AudioClip ac = Applet.newAudioClip(ClassName.class.getClassLoader().getResource(“key.mp3”));;   //play once
ac.stop();   //stop playing
ac.loop();   //play continuously

3.JLayer API to play mp3

Download the JLayer library .

import following :

import javazoom.jl.player.Player;
Sample code :
FileInputStream mp3_file=new FileInputStream("key.mp3");
Player mp3=new Player(mp3_file);;
catch(Exception e)
System.out.println("Error while playing audio "+e.getMessage());

Ok.. that’s not all.There is one little problem.
While playing this, any other code won’t run.Which means your app will freeze until music stops playing.

Following is the enhanced code that uses Thread to make it work.

public class Player implements Runnable{

 Thread musicThread = new Thread(this);
 AdvancedPlayer mp3Player;

  public void loadMusic(){
        mp3Player = new AdvancedPlayer(PlayerView.class.getClassLoader().getResourceAsStream(filename.mp3));  //input stream of mp3 file bundled in JAR file
             } catch (JavaLayerException ex){
                System.out.println(“Exception while loading file “+ex);

           } catch (FileNotFoundException ex) {
                System.out.println(“Audio file not found “+ex);


public void playMusic(){

public void run() {
         try {
        } catch (JavaLayerException ex) {
            System.out.println(“Error while playing audio “+ ex);

Note: If mp3spi1.9.5.jar and tritonus_share.jar (Javazoom project)are kept in classpath, using the java.applet package mp3 file can be played. Link to download mp3spi.

You may also like...

Leave a Reply

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