Playing a .wav in Java

Viewed 5724

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();
        }
    }
}
0 Answers
Related