如何向 Java JFrame 添加一些声音? [英] How can I add some sound to my Java JFrame?

查看:41
本文介绍了如何向 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?

推荐答案

播放.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆