Advertisement
dburyak

java audio playback

Jan 3rd, 2022
1,158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.16 KB | None | 0 0
  1. import javax.sound.sampled.AudioInputStream;
  2. import javax.sound.sampled.AudioSystem;
  3. import javax.sound.sampled.Clip;
  4. import javax.sound.sampled.LineEvent;
  5. import java.io.File;
  6. import java.util.concurrent.CountDownLatch;
  7.  
  8. public class Main {
  9.  
  10.     public static void main(String[] args) throws InterruptedException {
  11.         playSound("/home/dburyak/Downloads/CantinaBand3.wav");
  12.         System.out.println("End");
  13.     }
  14.  
  15.     public static void playSound(final String url) {
  16.         try {
  17.             Clip clip = AudioSystem.getClip();
  18.             var playbackFinished = new CountDownLatch(1);
  19.             // set listener first, before starting the pipeline
  20.             clip.addLineListener(e -> {
  21.                 if (e.getType() == LineEvent.Type.STOP) {
  22.                     playbackFinished.countDown();
  23.                 }
  24.             });
  25.             File file = new File(url);
  26.             AudioInputStream inputStream = AudioSystem.getAudioInputStream(file);
  27.             clip.open(inputStream);
  28.  
  29.             clip.start();
  30.             playbackFinished.await();
  31.         } catch (Exception e) {
  32.             System.err.println(e.getMessage());
  33.         }
  34.     }
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement