Skip to main content

Playing default system sounds in Java

Posted by mkarg on January 3, 2010 at 7:32 AM PST

It took me several sleepless nights to find out, but finally I got it - and was astonished how easy it is. Ever wanted to play the default system sound for a specific operation? Well, in fact there is no platform independent solution for that (can't believe it, I know, but it is true). But at least Swing internally does it that way on the Windows platform (and on other platforms it will just do nothing, so it is at least safe not to crash on other platforms):

 final Runnable runnable = Toolkit.getDefaultToolkit().getDesktopProperty("win.sound.exclamation");
if (runnable != null)
   runnable.run();

Yes, folk's, it's really such easy!

But what to do on other platforms? I don't know, actually. Maybe someone else ever might find out. Or Sun creates an API for that. :-)

So you like playing more sounds? Just change the name of the String property. A list of all possible values can be found here: java.sun.com/j2se/1.4.2/docs/guide/swing/1.4/w2k_props.html

Related Topics >>

Comments

depending on your intent...

... you might want to do this:
Toolkit.getDefaultToolkit().beep();
or if it's related to a component:
UIManager.getLookAndFeel().provideErrorFeedback(component);
Granted, not exactly the same as playing the default system sound, but handles the most common need for playing the default sound...

It's not about playing "some" sound

Maybe it was not clear enough in the blog posting: Windows (and other OS) know several default sounds, e. g. one for warnings and one for errors. See http://java.sun.com/j2se/1.4.2/docs/guide/swing/1.4/w2k_props.html (check for win.sound). The solution described in the blog posting describes how the programmer can choose which default sound is getting played. Your solution is working, but the programmer cannot tell which event's sound the system shall play - the system will just play some sound but, which possibly is not the sound of the event the programmer wanted to hear.