问题
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:
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);
}
}
来源:https://stackoverflow.com/questions/64509691/how-can-i-add-some-sound-to-my-java-jframe