Determining When a Sampled Audio Player Has Finished Playing - Java Media

Java examples for Media:Audio

Description

Determining When a Sampled Audio Player Has Finished Playing

Demo Code

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

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 Main {
  public static void main(String[] argv) {
    try {/* ww w  .j a  v  a2 s . co m*/
      AudioInputStream stream = AudioSystem.getAudioInputStream(new File(
          "audiofile"));

      stream = AudioSystem.getAudioInputStream(new URL(
          "http://hostname/audiofile"));

      AudioFormat format = stream.getFormat();
      if (format.getEncoding() != AudioFormat.Encoding.PCM_SIGNED) {
        format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
            format.getSampleRate(), format.getSampleSizeInBits() * 2,
            format.getChannels(), format.getFrameSize() * 2,
            format.getFrameRate(), true); // big endian
        stream = AudioSystem.getAudioInputStream(format, stream);
      }

      DataLine.Info info = new DataLine.Info(Clip.class, stream.getFormat(),
          ((int) stream.getFrameLength() * format.getFrameSize()));
      Clip clip = (Clip) AudioSystem.getLine(info);
      clip.open(stream);
      clip.addLineListener(new LineListener() {
        public void update(LineEvent evt) {
          if (evt.getType() == LineEvent.Type.STOP) {
          }
        }
      });
      clip.start();
    } catch (MalformedURLException e) {
    } catch (IOException e) {
    } catch (LineUnavailableException e) {
    } catch (UnsupportedAudioFileException e) {
    }
  }

}

Related Tutorials