Pregunta

Estoy tan confundido sobre por qué esto termina de inmediato...El depurador hasta ahora no ha sido de gran ayuda.Estoy seguro de que el código se ejecuta en todo momento.

import java.io.File;

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;

/**
 * An example of loading and playing a sound using a Clip. This complete class
 * isn't in the book ;)
 */
public class ClipTest {

  public static void main(String[] args) throws Exception {

    // specify the sound to play
    // (assuming the sound can be played by the audio system)
    File soundFile = new File("C:\\Users\\Benny\\Desktop\\AudioSample\\Austin.wav");
    AudioInputStream sound = AudioSystem.getAudioInputStream(soundFile);

    // load the sound into memory (a Clip)
    DataLine.Info info = new DataLine.Info(Clip.class, sound.getFormat());
    Clip clip = (Clip) AudioSystem.getLine(info);
    clip.open(sound);
    // due to bug in Java Sound, explicitly exit the VM when
    // the sound has stopped.
    clip.addLineListener(new LineListener() {
      public void update(LineEvent event) {
        if (event.getType() == LineEvent.Type.STOP) {
          event.getLine().close();
          System.exit(0);
        }
      }
    });
    // play the sound clip
    clip.start();
  }
} 
¿Fue útil?

Solución

el llamado a clip.start() hace que el sonido se reproduzca en un hilo diferente, concretamente en el hilo "Java Sound Event Dispatcher".El hilo principal continúa normalmente y se sale de la aplicación.

Dependiendo de cómo y cuando exactamente lo que desea reproducir este clip, existen diferentes soluciones.Muy a menudo, no son necesarias precauciones adicionales.Por ejemplo, en un juego, quieres reproducir sonidos del juego, pero cuando el juego sale, no se deben reproducir más sonidos.Y por lo general, lo harás no salir de la aplicación con System.exit(0) en absoluto, y especialmente no después de que un clip arbitrario haya terminado de reproducirse...

Sin embargo, en este ejemplo, podría utilizar un CountDownLatch.

final CountDownLatch clipDone = new CountDownLatch(1);
clip.addLineListener(new LineListener() {
    @Override
    public void update(LineEvent event) {
        if (event.getType() == LineEvent.Type.STOP) {
            event.getLine().close();
            clipDone.countDown();
        }
    }
});
// play the sound clip and wait until it is done
clip.start();
clipDone.await();
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top