Trouble playing wav in Java

前端 未结 1 666
野的像风
野的像风 2020-11-29 05:51

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 approac

相关标签:
1条回答
  • 2020-11-29 05:59

    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?

    import javax.sound.sampled.*;
    import java.io.File;
    import java.io.IOException;
    import javax.sound.sampled.LineEvent.Type;
    
    private static void playClip(File clipFile) throws IOException, 
      UnsupportedAudioFileException, LineUnavailableException, InterruptedException {
      class AudioListener implements LineListener {
        private boolean done = false;
        @Override public synchronized void update(LineEvent event) {
          Type eventType = event.getType();
          if (eventType == Type.STOP || eventType == Type.CLOSE) {
            done = true;
            notifyAll();
          }
        }
        public synchronized void waitUntilDone() throws InterruptedException {
          while (!done) { wait(); }
        }
      }
      AudioListener listener = new AudioListener();
      AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(clipFile);
      try {
        Clip clip = AudioSystem.getClip();
        clip.addLineListener(listener);
        clip.open(audioInputStream);
        try {
          clip.start();
          listener.waitUntilDone();
        } finally {
          clip.close();
        }
      } finally {
        audioInputStream.close();
      }
    }
    
    0 讨论(0)
提交回复
热议问题