如何为Java JFrame添加声音? [英] How can I add some sound to my Java JFrame?
本文介绍了如何为Java JFrame添加声音?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在用JFrame开发Java游戏.游戏即将完成,但我想添加一些声音.就像游戏开始时一样,声音也应该开始.我已经检查了Internet,但是代码不起作用或时间太长.谁能帮我提供一些可以在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?
推荐答案
播放.wav文件的基本示例:
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);
}
}
这篇关于如何为Java JFrame添加声音?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文