4

I know, another one. Thing is, I've looked through every thread I can find, and this problem is still persisting- I get no error, my headphones 'pop' like they're about to play sound, but nothing plays. There is a delay before the program terminates, but whether it's a an indication of anything or just Java closing I can't tell.

import java.io.File;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;

public class Main {
    public static void main(String[] args) {
        try{
//          AudioInputStream ais = AudioSystem.getAudioInputStream(Main.class.getResource("bells.wav"));
            AudioInputStream ais = AudioSystem.getAudioInputStream(new File("bells.wav"));
            Clip test = AudioSystem.getClip();
            test.open(ais);
            test.start();
            test.drain();
            test.close();
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }
}

EDIT: Now working code:

import java.io.File;
import javax.sound.sampled.*;

public class Main {
    public static void main(String[] args) {        
        try{
            AudioInputStream ais = AudioSystem.getAudioInputStream(new File("bells.wav"));
            Clip test = AudioSystem.getClip();  

            test.open(ais);
            test.start();

            while (!test.isRunning())
                Thread.sleep(10);
            while (test.isRunning())
                Thread.sleep(10);

            test.close();
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }
}
Overt_Agent
  • 510
  • 6
  • 15
  • @gpasch I did, yes, and tried with and without. Thanks. – Overt_Agent Mar 25 '16 at 01:20
  • Also @gpasch, for the record, the official documentation uses clip.close() at the end of their example. – Overt_Agent Mar 25 '16 at 01:25
  • 1
    For anyone interested, the footnote on the 3rd answer down here solved it: http://stackoverflow.com/questions/2416935/how-to-play-wav-files-with-java - The problem is that Clip.drain(); isn't thread blocking like it should be. I've updated the main post with my (now working) code for future reference – Overt_Agent Mar 25 '16 at 01:42
  • 1
    You shouldn't actually spin like that answer suggests, as the comment below it says. Also, it won't be a problem in a normal application which already has a main thread. Other examples that show a `LineListener` are much better. `LineListener` will tell you when a Clip is done. I'm glad you found the problem, though. – Radiodef Mar 25 '16 at 01:50

0 Answers0