How can I add some sound to my Java JFrame? [closed]

旧巷老猫 提交于 2021-02-05 12:20:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!