Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Well, the title says all, I tried playing a wav file using javax.sound and nothing is happening. I have tried many different files without any luck.

public static void main(String[] args) throws IOException, UnsupportedAudioFileException, LineUnavailableException
{

    File in = new File("C:\Users\Sandra\Desktop\music\rags.wav");
    AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(in);
    Clip play = AudioSystem.getClip();
    play.open(audioInputStream);
    FloatControl volume= (FloatControl) play.getControl(FloatControl.Type.MASTER_GAIN);
    volume.setValue(1.0f); // Reduce volume by 10 decibels.
    play.start();

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
216 views
Welcome To Ask or Share your Answers For Others

1 Answer

As, has already begin stated, you need to prevent the main thread from exiting, as this will cause the JVM to terminate.

Clip#start is not a blocking call, meaning that it will return (soon) after it is called.

I have no doubt that there are many ways to approach this problem and this is just a simple example of one of them.

public class PlayMusic {

    public static void main(String[] args) throws InterruptedException {
        Clip play = null;
        try {
            File in = new File("C:\Users\Public\Music\Sample Music\Kalimba.wav");
            AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(in);
            play = AudioSystem.getClip();
            play.open(audioInputStream);
            FloatControl volume = (FloatControl) play.getControl(FloatControl.Type.MASTER_GAIN);
            volume.setValue(1.0f); // Reduce volume by 10 decibels.
            play.start();
            // Loop until the Clip is not longer running.
            // We loop this way to allow the line to fill, otherwise isRunning will
            // return false
            //do {
            //    Thread.sleep(15);
            //} while (play.isRunning());
            play.drain();
        } catch (UnsupportedAudioFileException | IOException | LineUnavailableException ex) {
            ex.printStackTrace();
        } finally {
            try {
                play.close();
            } catch (Exception exp) {
            }
        }
        System.out.println("...");
    }
}

The actual solution will depend on your needs.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...