Java 相当于 C# system.beep?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10771441/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java equivalent of C# system.beep?
提问by Glen654
I am working on a Java program, and I really need to be able to play a sound by a certain frequency and duration, similarly to the c# method System.Beep, I know how to use it in C#, but I can't find a way to do this in Java. Is there some equivalent, or another way to do this?
我正在做一个Java程序,我真的需要能够以一定的频率和持续时间播放声音,类似于c#方法System.Beep,我知道如何在C#中使用它,但我找不到一种在 Java 中执行此操作的方法。是否有一些等效的或另一种方法可以做到这一点?
using System;
class Program
{
static void Main()
{
// The official music of Dot Net Perls.
for (int i = 37; i <= 32767; i += 200)
{
Console.Beep(i, 100);
}
}
}
采纳答案by Stephen C
I don't think there's a way to play tunes1with "beep" in portable2Java. You'll need to use the javax.sound.*APIs I think ... unless you can find a third-party library that simplifies things for you.
我认为没有办法在便携式2Java 中播放带有“哔”声的曲调1。您将需要使用我认为的API ……除非您能找到可以为您简化事情的第三方库。javax.sound.*
If you want to go down this path, then this pagemight give you some ideas.
如果你想沿着这条路走下去,那么这个页面可能会给你一些想法。
1 - Unless your users are all tone-deaf. Of course you can do things like beeping in Morse code ... but that's not a tune.
1 - 除非您的用户都是聋哑人。当然,你可以用莫尔斯电码发出哔哔声之类的东西……但这不是调子。
2 - Obviously, you could make native calls to a Windows beep function. But that would not be portable.
2 - 显然,您可以对 Windows 蜂鸣功能进行本机调用。但这不会是便携式的。
回答by Hunter McMillen
You can use this:
你可以使用这个:
java.awt.Toolkit.getDefaultToolkit().beep();
EDIT
编辑
If you are trying to play anything of duration and with different sounds you should really look into the Java MIDI library. The default beep won't be able to meet your needs as you can't change the length of the beep.
如果您尝试播放任何持续时间不同的声音,您应该真正查看 Java MIDI 库。默认蜂鸣声无法满足您的需求,因为您无法更改蜂鸣声的长度。
回答by Bhavik Ambani
回答by Adrian
Just print it:
只需打印它:
System.out.println("/**
* Beeps. Currently half-assumes that the format the system expects is
* "PCM_SIGNED unknown sample rate, 16 bit, stereo, 4 bytes/frame, big-endian"
* I don't know what to do about the sample rate. Using 11025, since that
* seems to be right, by testing against A440. I also can't figure out why
* I had to *4 the duration. Also, there's up to about a 100 ms delay before
* the sound starts playing.
* @param freq
* @param millis
*/
public static void beep(double freq, final double millis) {
try {
final Clip clip = AudioSystem.getClip();
AudioFormat af = clip.getFormat();
if (af.getSampleSizeInBits() != 16) {
System.err.println("Weird sample size. Dunno what to do with it.");
return;
}
//System.out.println("format " + af);
int bytesPerFrame = af.getFrameSize();
double fps = 11025;
int frames = (int)(fps * (millis / 1000));
frames *= 4; // No idea why it wasn't lasting as long as it should.
byte[] data = new byte[frames * bytesPerFrame];
double freqFactor = (Math.PI / 2) * freq / fps;
double ampFactor = (1 << af.getSampleSizeInBits()) - 1;
for (int frame = 0; frame < frames; frame++) {
short sample = (short)(0.5 * ampFactor * Math.sin(frame * freqFactor));
data[(frame * bytesPerFrame) + 0] = (byte)((sample >> (1 * 8)) & 0xFF);
data[(frame * bytesPerFrame) + 1] = (byte)((sample >> (0 * 8)) & 0xFF);
data[(frame * bytesPerFrame) + 2] = (byte)((sample >> (1 * 8)) & 0xFF);
data[(frame * bytesPerFrame) + 3] = (byte)((sample >> (0 * 8)) & 0xFF);
}
clip.open(af, data, 0, data.length);
// This is so Clip releases its data line when done. Otherwise at 32 clips it breaks.
clip.addLineListener(new LineListener() {
@Override
public void update(LineEvent event) {
if (event.getType() == Type.START) {
Timer t = new Timer((int)millis + 1, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
clip.close();
}
});
t.setRepeats(false);
t.start();
}
}
});
clip.start();
} catch (LineUnavailableException ex) {
System.err.println(ex);
}
}
7")
Works on Windows and MacOS.
适用于 Windows 和 MacOS。
回答by Erhannis
I've hacked together a function that works for me. It uses a bunch of stuff from javax.sound.sampled. I've geared it to work with the audio format my system automatically gives a new Clip from AudioSystem.getClip(). There's probably all kinds of ways it could be made more robust and more efficient.
我已经编写了一个对我有用的函数。它使用了一堆来自javax.sound.sampled. 我已将其调整为使用我的系统自动提供的新剪辑的音频格式AudioSystem.getClip()。可能有各种各样的方法可以使它更健壮和更高效。
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);
}
EDIT: Apparently somebody's improved my code. I haven't tried it yet, but give it a go: https://gist.github.com/jbzdak/61398b8ad795d22724dd
编辑:显然有人改进了我的代码。我还没有尝试过,但试一试:https: //gist.github.com/jbzdak/61398b8ad795d22724dd
回答by EFalco
Another solution, Windows dependent is to use JNA and call directly Windows Beep function, available in kernel32. Unfortunately Kernel32 in JNA doesn't provide this method in 4.2.1, but you can easily extend it.
另一个解决方案,Windows 依赖是使用 JNA 并直接调用 Windows Beep 函数,在 kernel32 中可用。不幸的是,JNA 中的 Kernel32 在 4.2.1 中没有提供这种方法,但您可以轻松扩展它。
static public void main(String... args) throws Exception {
Kernel32 kernel32 = (Kernel32) Native.loadLibrary("kernel32", Kernel32.class);
kernel32.Beep(800, 3000);
}
To use it :
使用它:
<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>
If you use maven you have to add the following dependencies :
如果使用 maven,则必须添加以下依赖项:
package javaapplication2;
import java.applet.Applet;
import java.applet.AudioClip;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
public class JavaApplication2 {
public static void main(String[] args) throws MalformedURLException {
File file = new File("/path/to/your/sounds/beep3.wav");
URL url = null;
if (file.canRead()) {url = file.toURI().toURL();}
System.out.println(url);
AudioClip clip = Applet.newAudioClip(url);
clip.play();
System.out.println("should've played by now");
}
}
//beep3.wav was available from: http://www.pacdv.com/sounds/interface_sound_effects/beep-3.wav
回答by Nav
回答by marcolopes
If you're using SWT widgets, you can do it this way (SYSTEM SOUND BEEP!)
如果您正在使用 SWT 小部件,您可以这样做(系统声音提示!)
##代码##if you want NATIVE JAVA, here is a class for it: https://github.com/marcolopes/dma/blob/master/org.dma.java/src/org/dma/java/util/SoundUtils.java
如果你想要原生 JAVA,这里有一个类:https: //github.com/marcolopes/dma/blob/master/org.dma.java/src/org/dma/java/util/SoundUtils.java

