Saturday, August 29, 2015

Play audio file in Java

Couple of week ago I needed to implement audio tone play in a Java application and I could not able to find clear reference which developers can refer So I though to put a blog post on this. In this post I am going to show show to play audio file using Java.

Prerequisites 
  1. You should have install java in your PC and set path variable correctly (JAVA_HOME, JRE_HOME)
  2. You should have install Eclipse Java EE LUNA 4.4 IDE or any IDE you preferred (In this post I'm Using Eclipse )

Step 1 Create Java project 

As first step lets create simple Java Project using Eclipse. Go to File->New->Java Project. Give preferred name to project. I'm going to name the project as "AudioPlay". Then find some Audio file you need to play. Then create new package call "resource" inside the src directory and added the audio in to that package.

 


Step 2 Create java class to play audio 

As next step lets create the Java class to play our selected audio. To add new class go to default package and right click on it then go to New->Class. I'll give class name as "AdvancedPlayer.java". Then add following content in to that class.


import java.io.File;
import java.io.IOException;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineListener;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;


public class AdvancedPlayer implements LineListener {
boolean playCompleted;
    
    /**
     * Play a audio file which pass as audioFilePath 
     * @param audioFilePath Absolute path of the audio file.
     */
    void playAudioFile(String audioFilePath) {
        File audioFile = new File(audioFilePath);
 
        try {
            AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(audioFile);
 
            AudioFormat audioFormat = audioInputStream.getFormat();
 
            DataLine.Info formatInfo = new DataLine.Info(Clip.class, audioFormat);
 
            Clip clip = (Clip) AudioSystem.getLine(formatInfo);
 
            clip.addLineListener(this);
 
            clip.open(audioInputStream);
             
            clip.start();
             
            while (!playCompleted) {
                // wait for the playback completes
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            }
             
            clip.close();
             
        } catch (UnsupportedAudioFileException e) {
            System.out.println("Error on not supporting file format");
            e.printStackTrace();
        } catch (LineUnavailableException e) {
            System.out.println("Error occured due to unavailable of Audio line for playing.");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("Error occured in audio play.");
            e.printStackTrace();
        }
         
    }

@Override
public void update(LineEvent event) {
// TODO Auto-generated method stub
}
public static void main(String[] args) {
AdvancedPlayer player=new AdvancedPlayer();
String audioFilePath="resource/Alarm01.wav";
String absolutePath=AdvancedPlayer.class.getResource(audioFilePath).getFile().toString();
player.playAudioFile(absolutePath);
}
}
  
Then our final project will be look similar to below screenshot. Now just run the AdvancedPlayer class and you can here the audio that you have added in to resource.

Figure 2 : Project structure



No comments:

Post a Comment