Java Sound not Playing

Viewed 330

I know this problem has been queried previously, and I have looked at the responses and tried to implement them, but so far nobody's solutions seem to be working for me. Please can anyone have a look at my code and help me figure out why the program ends instantly, and no sound is played....? thanks in advance

import javax.sound.sampled.*;
import java.io.*;
import java.net.URL;

public class SoundPlayer {

    public SoundPlayer() {
    }

    public static void play(String file) {
        File sound = new File(file);
        try {
            String url = sound.toURI().toURL().toString();
            System.out.println(url);
            Clip clip = AudioSystem.getClip();
            clip.open(AudioSystem.getAudioInputStream(new URL(url)));
            clip.start();
            clip.loop(Clip.LOOP_CONTINUOUSLY);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        SoundPlayer player = new SoundPlayer();
        player.play("sounds/1.wav");

    }
}
3 Answers

OK, so the answer is to include

Thread.sleep(1000000);

When you execute a file (a .wav sound file in your case) it is active as long as your code is beign executed so when the execution is over it stops in your case the only code to be executed is to play the .wav file and then the execution is over the sound plays but stops so fast.

The solution as you suggested Thread.sleep(time) is there to keep the execution for the time chosen and then it stops and the sound file with it. You can use a while loop to hold the execution running for as long as the there is code to execute and that means the audio file will play along with it (you have used clip.loop(Clip.LOOP_CONTINUOUSLY); )

Your program is an example of multi-threaded coding. The command clip.start() launches a new, concurrently running thread and then proceeds to the next line of code without pause. Your thread then sets the loop flag, and finishes.

Meanwhile, the concurrent "play" thread is executing. But this thread has been given "daemon" status. Regular threads will keep a program running until they are finished, but "daemon" status threads will allow themselves to be halted if there are no regular threads alive. So, when the "main" thread is done, the audio-playback thread also quits.

API info about threads.

When a Clip launches a new thread with the start() method, the thread is automatically given daemon status.

It baffles me, though, that I cannot find any API documentation about the status of the new thread launched by Clip. Nor is there mention of this in Oracle's Playing Back Audio tutorial. So you, and countless other people using the Clip object for the first time can hardly be faulted for being mystified when this happens.

Related