How do I create a beep sound?

package org.kodejava.awt;

import java.awt.*;

public class BeepExample {
    public static void main(String[] args) {
        // This is the way we can send a beep audio out.
        Toolkit.getDefaultToolkit().beep();
    }
}

Using Runtime.exec() method we can do something like the code snippet below to produce beep sound using powershell command.

try {
    Process process = Runtime.getRuntime().exec(
            new String[]{"powershell", "[console]::beep()"});

    int errorCode = process.waitFor();
    int exitValue = process.exitValue();
    System.out.println("errorCode = " + errorCode);
    System.out.println("exitValue = " + exitValue);
} catch (Exception e) {
    throw new RuntimeException(e);
}

We can also execute external command using ProcessBuilder class like the following code snippet:

try {
    ProcessBuilder processBuilder = new ProcessBuilder();
    processBuilder.command("powershell", "[console]::beep()");
    Process process = processBuilder.start();

    int errorCode = process.waitFor();
    int exitValue = process.exitValue();
    System.out.println("errorCode = " + errorCode);
    System.out.println("exitValue = " + exitValue);
} catch (Exception e) {
    throw new RuntimeException(e);
}
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.