Use PC Speaker from Java

Getting the PC speaker to emit a annoying beep might seem to be a quite easy task. And it is provided that you are in a graphical environment such as [http://www.x.org/ X.org] och [http://www.microsoft.com/windows/ MS Windows™]. Then using this easy bit of code will do:

package beeptest;
 
import java.awt.Toolkit;
 
public class BeepTest {
        public static void main(String[] args) {
                try {
                        Toolkit.getDefaultToolkit().beep();
                } catch (Exception e) {
                        e.printStackTrace();
                }
        }
}

But if you (like me) wants to run a console application ''Toolkit.getDefaultToolkit().beep();'' seems to do nothing. Then the following lines will do (at lest on [http://www.kernel.org/ Linux®] based operating systems).

package beeptest;
 
public class BeepTest2 {
        public static void main(String[] args) {
                try {
                        System.out.print ( "\007" );
                        System.out.flush(); 
                } catch (Exception e) {
                        e.printStackTrace();
                }
        }
}
Tags: