我有两个问题 - (1) 如何播放小声音片段,例如飞碟飞行、子弹射击、物体被子弹击中等等。声音非常短,但实时。我喜欢旧的街机声音,所以它们不需要很大的 .wav。我想用尽可能少的代码来运行它们。这引出了我的第二个问题...... (2) 有谁知道在哪里可以找到这些声音片段。
请注意,我在这里看到了一些答案,但它们似乎不完整。如果您有一个直接的通用代码,那就太好了!我对声音知之甚少,因为我通常不会在游戏写作中做到这一点。
感谢您提供的所有信息 - 我非常感激!
最佳答案
使用javax.sound,可以实现简单的音效。
<小时/>编辑:使用线程(或不使用线程)
import javax.sound.sampled.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class AppWithSound2 extends JFrame implements ActionListener {
JButton b1;
JButton b2;
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
AppWithSound2 app = new AppWithSound2();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.startApp();
}
});
}
public AppWithSound2() {
initGUI();
}
private void startApp() {
setVisible(true);
}
private void initGUI() {
setLayout(new FlowLayout());
setSize(300, 200);
b1 = new JButton("Sound with no thread");
b2 = new JButton("Sound with thread");
b1.addActionListener(this);
b2.addActionListener(this);
add(b1);
add(b2);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == b1) {
LaserSound.laser();
}
if (e.getSource() == b2) {
new LaserSound().start();
}
}
}
class LaserSound extends Thread {
public void run() {
LaserSound.laser();
}
public static void laser() {
int repeat = 10;
try {
AudioFormat af = new AudioFormat(8000f, // sampleRate
8, // sampleSizeInBits
1, // channels
true, // signed
false); // bigEndian
SourceDataLine sdl;
sdl = AudioSystem.getSourceDataLine(af);
sdl.open(af);
sdl.start();
byte[] buf = new byte[1];
int step;
for (int j = 0; j < repeat; j++) {
step = 10;
for (int i = 0; i < 2000; i++) {
buf[0] = ((i % step > 0) ? 32 : (byte) 0);
if (i % 250 == 0)
step += 2;
sdl.write(buf, 0, 1);
}
Thread.sleep(200);
}
sdl.drain();
sdl.stop();
sdl.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
关于应用程序中的 Java 游戏声音(例如,而不是小程序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3392449/