另一个依赖于 Windows 的解决方案是使用 JNA 并直接调用 Windows Beep 函数,在 kernel32 中可用。不幸的是,JNA 中的 Kernel32 在 4.2.1 中没有提供此方法,但您可以轻松扩展它。
public interface Kernel32 extends com.sun.jna.platform.win32.Kernel32 {
/**
* Generates simple tones on the speaker. The function is synchronous;
* it performs an alertable wait and does not return control to its caller until the sound finishes.
*
* @param dwFreq : The frequency of the sound, in hertz. This parameter must be in the range 37 through 32,767 (0x25 through 0x7FFF).
* @param dwDuration : The duration of the sound, in milliseconds.
*/
public abstract void Beep(int dwFreq, int dwDuration);
}
要使用它:
static public void main(String... args) throws Exception {
Kernel32 kernel32 = (Kernel32) Native.loadLibrary("kernel32", Kernel32.class);
kernel32.Beep(800, 3000);
}
如果使用 maven,则必须添加以下依赖项:
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna</artifactId>
<version>4.2.1</version>
</dependency>
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna-platform</artifactId>
<version>4.2.1</version>
</dependency>