如何在我的Java JFrame中添加一些声音?

huangapple go评论82阅读模式
英文:

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);
	}
}

huangapple
  • 本文由 发表于 2020年10月24日 11:31:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/64509691.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定