tags:

views:

624

answers:

1

I'm trying to play a

PCM_UNSIGNED 11025.0 Hz, 8 bit, mono, 1 bytes/frame

file as described here (1) and here(2).

The first approach works, but I don't want to depend on sun.* stuff. The second results in just some leading frames being played, that sounds more like a click. Can't be an IO issue as I'm playing from a ByteArrayInputStream.

Plz share your ideas on why might this happen. TIA.

+1  A: 

I'm not sure why the second approach you linked to starts another thread; I believe the audio will be played in its own thread anyway. Is the problem that your application finishes before the clip has finished playing?

As Jataro comments, you can use the drain method to block until the audio has completed:

  /**
   * Plays sound file and blocks until finished.
   */
  private static void playClip(File soundFile)
      throws IOException, UnsupportedAudioFileException,
      LineUnavailableException {
    AudioInputStream audioInputStream = AudioSystem
        .getAudioInputStream(soundFile);
    try {
      Clip clip = AudioSystem.getClip();
      clip.open(audioInputStream);
      try {
        clip.start();
        clip.drain();
      } finally {
        clip.close();
      }
    } finally {
      audioInputStream.close();
    }
  }
McDowell
In fact I don't run it in a separate thread, just linked that for brevity.THANKS A LOT!!!
alex
@Jataro - you are correct; I had missed that call in the API; I'll update the code.
McDowell