tags:

views:

42

answers:

4

Hello,

I am working with a SMS handling, java based software and want to play a beep / alert sound whenever we receive a message. I tried looking at the java.sound libraries and could not find anything. I do not know if going the applet way of playing a sound will be okay in a java application! Are there any predefined sounds in any java libraries which we can call in an application? Any pointers will be appreciated!

+2  A: 

You can take a look at the beep method within the Toolkit class, as shown here

npinti
A: 

The applet route should be fine (and is very straightforward). To avoid creating an Applet instance you can use the static newAudioClip method, and then call play() on the AudioClip created.

URL url = getClass().getResource("/foo/bar/sound.wav");
AudioClip clip = Applet.newAudioClip(url);
clip.play();
Adamski
A: 

If you just want a beep or quick alert try

Toolkit.getDefaultToolkit().beep();
Sean
A: 

If you want to use the sound package to play an arbitrary sound file, you can use the javax.sound.sampled package. Here is the code that will play a sound file:

private void playSound(File f) {
    Runnable r = new Runnable() {
        private File f;

        public void run() {
            playSoundInternal(this.f);
        }

        public Runnable setFile(File f) {
            this.f = f;
            return this;
        }
    }.setFile(f);

    new Thread(r).start();
}

private void playSoundInternal(File f) {
    try {
        AudioInputStream audioInputStream = udioSystem.getAudioInputStream(f);
        try {
            Clip clip = AudioSystem.getClip();
            clip.open(audioInputStream);
            try {
                clip.start();
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                clip.drain();
            } finally {
                clip.close();
            }
        } catch (LineUnavailableException e) {
            e.printStackTrace();
        } finally {
            audioInputStream.close();
        }
    } catch (UnsupportedAudioFileException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Erick Robertson