Thursday, August 11, 2011

Working with Java Sound API

Recently had a chance to work with Java Sound API where I am able to play and record sound through my laptop speaker and microphone.

I used below code to play a wav clip.

public class PlaySound
{
     private void playClip()
    {
        try {
            File file = new File("Z:\\songs\\song.wav");
            AudioInputStream audioStream = AudioSystem.getAudioInputStream(file);
            AudioFormat format = audioStream.getFormat();
            DataLine.Info info = new DataLine.Info(Clip.class,format);
            Clip clip = (Clip) AudioSystem.getLine(info);   
            clip.addLineListener(this);
            clip.open(audioStream);

            clip.loop(5);
        } catch (LineUnavailableException ee) {
            ee.printStackTrace();
        }
        catch(IOException ee)
        {
            ee.printStackTrace();
        }
        catch(Exception ee)
        {
            ee.printStackTrace();
        }
    }


    public static void main(String a[])
   {
          new PlaySound().playClip();
   }

}

My bad, it was not working. After struggling to find the reason, finally found that 
Clip clip = (Clip) AudioSystem.getLine(info); 

is creating a new Sound Dispatcher daemon thread which expects some non daemon thread to run in the jvm. Finally added some Thread.sleep(5000) in the main method to keep jvm running and it started working.