英文:
How can I add some sound to my Java JFrame?
问题
我正在使用JFrame制作一个Java游戏。游戏几乎完成,但我想为其添加一些音效。比如当游戏开始时,声音也应该开始播放。我已经在互联网上查找过,但那些代码要么无法正常工作,要么非常冗长。有人可以帮我提供一些在JFrame中可行的简单代码吗?
英文:
I am making a Java game in JFrame. The game is almost completed but I want to add some sound to it. Like when the game will start, the sound should also start. I have checked the Internet but the codes are either not working or are very long. Can anyone help me provide some easy codes that will work in JFrame?
答案1
得分: 2
基本的播放 .wav 文件的示例:
import java.awt.event.*;
import javax.swing.*;
import javax.sound.sampled.*;
import java.net.URL;
import java.io.*;
class SoundTest
{
public static void main(String[] args) throws Exception
{
// URL file = new URL("file:./flyby1.wav");
// URL file = new URL("file:c:/users/netro/java/flyby1.wav");
URL file = new URL("https://www.wavsource.com/snds_2020-10-01_3728627494378403/sfx/air_raid.wav");
AudioInputStream ais = AudioSystem.getAudioInputStream(file);
Clip clip = AudioSystem.getClip();
clip.open(ais);
JButton button = new JButton("Play Clip");
button.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent ae)
{
clip.setFramePosition(0);
clip.start();
}
});
JOptionPane.showMessageDialog(null, button);
}
}
英文:
Basic example for playing a .wav file:
import java.awt.event.*;
import javax.swing.*;
import javax.sound.sampled.*;
import java.net.URL;
import java.io.*;
class SoundTest
{
public static void main(String[] args) throws Exception
{
//URL file = new URL("file:./flyby1.wav");
//URL file = new URL("file:c:/users/netro/java/flyby1.wav");
URL file = new URL("https://www.wavsource.com/snds_2020-10-01_3728627494378403/sfx/air_raid.wav");
AudioInputStream ais = AudioSystem.getAudioInputStream(file);
Clip clip = AudioSystem.getClip();
clip.open(ais);
JButton button = new JButton("Play Clip");
button.addActionListener( new ActionListener()
{
@Override
public void actionPerformed(ActionEvent ae)
{
clip.setFramePosition(0);
clip.start();
}
});
JOptionPane.showMessageDialog(null, button);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论