Clip Java.ouvrir se bloque indéfiniment


J'essaie d'ouvrir un .fichier wav et le lire à l'aide d'un clip. Mais quand j'appelle myClip.ouvrir(...), le fil se fige et ne reprend jamais. Aucune erreur n'est renvoyée. Voici une version simple de mon code:

try {
    AudioInputStream mySound = AudioSystem.getAudioInputStream(new File("sounds/myAudioFile.wav"));
    myClip = AudioSystem.getClip();
    myClip.open(mySound); //This is where it hangs
    myClip.start(); //This is never executed
} catch (Exception e) {e.printStackTrace();}

MODIFIER: Une autre version de mon code ne fonctionne pas):

Clip myClip = null;

new Thread(new Runnable() {
     public void run() {
          try {
              AudioInputStream mySound = AudioSystem.getAudioInputStream(new File("sounds/myAudioFile.wav"));
              myClip = AudioSystem.getClip();
              System.out.println("Before open");
              myClip.open(mySound); //This is where it hangs
              System.out.println("After open"); //never executed
              //This thread runs indefinitely, whether or not clip.start() is called
          } catch (Exception e) {e.printStackTrace();}
     }
}).start();

try{  Thread.sleep(1000);  }catch(Exception e){} //give it a second to open

myClip.start(); //Executed, but doesn't make a sound
System.out.println("Started clip");

Sortie:

Before open
Started clip

Je sais ce qui cause cela, mais je ne peux pas trouver un moyen pour le fil de geler éternellement. Il se fige parce que les pilotes sonores sur mon ordinateur s'arrêtent de temps en temps travail, et empêcher tout son de tout programme de jouer. J'ai juste besoin d'un moyen de forcer le clip.ouvrez la méthode (ou le thread) à timeout après environ 2 à 3 secondes. L'appel de clip.start () dans un autre thread fonctionne, mais ne joue aucun son car le clip ne s'est pas ouvert. Et le fil contenant clip.ouvrir(...) s'exécute pour toujours, même après avoir appelé clip.commencer().

Author: Daniel Williams, 2016-06-21

1 answers

public static synchronized void playSound(final String url) {
  new Thread(new Runnable() {
  // The wrapper thread is unnecessary, unless it blocks on the
  // Clip finishing; see comments.
    public void run() {
      try {
        Clip clip = AudioSystem.getAudioInputStream(new File("sounds/myAudioFile.wav"));       // you can pass it in url
        clip.open(inputStream);
      } catch (Exception e) {
        System.err.println(e.getMessage());
      }
    }
  }).start();
}

Encore un point: Tu n'as pas commencé ton clip. utilisez clip.commencer() Dans ce cas, vous n'aurez pas à utiliser un fil différent comme clip.start() génère un nouveau thread lui-même.

 0
Author: Boola, 2016-06-21 06:24:05