Open In App

How to play an Audio file using Java

Improve
Improve
Like Article
Like
Save
Share
Report

In this article we will see, how can we play an audio file in pure java, here pure means, we are not going to use any external library. You can create your own music player by the help of this article. Java inbuilt libraries support only AIFC, AIFF, AU, SND and WAVE formats.
There are 2 different interfaces which can be used for this purpose Clip and SourceDataLine. In this article, we will discuss playing audio file using Clip only and see the various methods of clip. We will cover following operations:

  1. Start.
  2. Pause.
  3. Resume.
  4. Restart.
  5. Stop
  6. Jump to a specific position of playback.

Play Audio using Clip

Clip is a java interface available in javax.sound.sampled package and introduced in Java7.
Following steps are to be followed to play a clip object.

  1. Create an object of AudioInputStream by using AudioSystem.getAudioInputStream(File file). AudioInputStream converts an audio file into stream.
  2. Get a clip reference object from AudioSystem.
  3. Stream an audio input stream from which audio data will be read into the clip by using open() method of Clip interface.
  4. Set the required properties to the clip like frame position, loop, microsecond position.
  5. Start the clip




// Java program to play an Audio
// file using Clip Object
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
  
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
  
public class SimpleAudioPlayer 
{
  
    // to store current position
    Long currentFrame;
    Clip clip;
      
    // current status of clip
    String status;
      
    AudioInputStream audioInputStream;
    static String filePath;
  
    // constructor to initialize streams and clip
    public SimpleAudioPlayer()
        throws UnsupportedAudioFileException,
        IOException, LineUnavailableException 
    {
        // create AudioInputStream object
        audioInputStream = 
                AudioSystem.getAudioInputStream(new File(filePath).getAbsoluteFile());
          
        // create clip reference
        clip = AudioSystem.getClip();
          
        // open audioInputStream to the clip
        clip.open(audioInputStream);
          
        clip.loop(Clip.LOOP_CONTINUOUSLY);
    }
  
    public static void main(String[] args) 
    {
        try
        {
            filePath = "Your path for the file";
            SimpleAudioPlayer audioPlayer = 
                            new SimpleAudioPlayer();
              
            audioPlayer.play();
            Scanner sc = new Scanner(System.in);
              
            while (true)
            {
                System.out.println("1. pause");
                System.out.println("2. resume");
                System.out.println("3. restart");
                System.out.println("4. stop");
                System.out.println("5. Jump to specific time");
                int c = sc.nextInt();
                audioPlayer.gotoChoice(c);
                if (c == 4)
                break;
            }
            sc.close();
        
          
        catch (Exception ex) 
        {
            System.out.println("Error with playing sound.");
            ex.printStackTrace();
          
          }
    }
      
    // Work as the user enters his choice
      
    private void gotoChoice(int c)
            throws IOException, LineUnavailableException, UnsupportedAudioFileException 
    {
        switch (c) 
        {
            case 1:
                pause();
                break;
            case 2:
                resumeAudio();
                break;
            case 3:
                restart();
                break;
            case 4:
                stop();
                break;
            case 5:
                System.out.println("Enter time (" + 0
                ", " + clip.getMicrosecondLength() + ")");
                Scanner sc = new Scanner(System.in);
                long c1 = sc.nextLong();
                jump(c1);
                break;
      
        }
      
    }
      
    // Method to play the audio
    public void play() 
    {
        //start the clip
        clip.start();
          
        status = "play";
    }
      
    // Method to pause the audio
    public void pause() 
    {
        if (status.equals("paused")) 
        {
            System.out.println("audio is already paused");
            return;
        }
        this.currentFrame = 
        this.clip.getMicrosecondPosition();
        clip.stop();
        status = "paused";
    }
      
    // Method to resume the audio
    public void resumeAudio() throws UnsupportedAudioFileException,
                                IOException, LineUnavailableException 
    {
        if (status.equals("play")) 
        {
            System.out.println("Audio is already "+
            "being played");
            return;
        }
        clip.close();
        resetAudioStream();
        clip.setMicrosecondPosition(currentFrame);
        this.play();
    }
      
    // Method to restart the audio
    public void restart() throws IOException, LineUnavailableException,
                                            UnsupportedAudioFileException 
    {
        clip.stop();
        clip.close();
        resetAudioStream();
        currentFrame = 0L;
        clip.setMicrosecondPosition(0);
        this.play();
    }
      
    // Method to stop the audio
    public void stop() throws UnsupportedAudioFileException,
    IOException, LineUnavailableException 
    {
        currentFrame = 0L;
        clip.stop();
        clip.close();
    }
      
    // Method to jump over a specific part
    public void jump(long c) throws UnsupportedAudioFileException, IOException,
                                                        LineUnavailableException 
    {
        if (c > 0 && c < clip.getMicrosecondLength()) 
        {
            clip.stop();
            clip.close();
            resetAudioStream();
            currentFrame = c;
            clip.setMicrosecondPosition(c);
            this.play();
        }
    }
      
    // Method to reset audio stream
    public void resetAudioStream() throws UnsupportedAudioFileException, IOException,
                                            LineUnavailableException 
    {
        audioInputStream = AudioSystem.getAudioInputStream(
        new File(filePath).getAbsoluteFile());
        clip.open(audioInputStream);
        clip.loop(Clip.LOOP_CONTINUOUSLY);
    }
  
}


In above program we have used AudioInputStream which is a class in Java to read audio file as a stream. Like every stream of java if it is to be used again it has to be reset.

  • To pause the playback we have to stop the player and store the current frame in an object. So that while resuming we can use it. When resuming we just have to play again the player from the last position we left.
    clip.getMicrosecondPosition() method returns the current position of audio and clip.setMicrosecondPosition(long position) sets the current position of audio.
  • To stop the playback, you must have to close the clip otherwise it will remain open. I have also used clip.loop(Clip.LOOP_CONTINOUSLY) for testing. Because wav files are generally small so I have played mine in a loop.
  • Important Points:

    1. Always close your opened stream and resources before exiting the program.
    2. You have to stop the clip before playing it again. So keep proper checks.
    3. If AudioInputStream is to be used again, it has to be reset.

     



    Last Updated : 03 Jul, 2022
    Like Article
    Save Article
    Previous
    Next
    Share your thoughts in the comments
Similar Reads