0

我一直在寻找这个问题的一些解决方案,但似乎没有任何帮助。

我正在尝试加载一个文件(“soundfile.wav”),这样我就可以在我的 playSound 方法中使用它。我希望它在导出时从 jarfile 加载,因此下载时看不到该文件。

package soundplayer;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.sound.sampled.*;
import javax.swing.*;

import java.io.*;

public class SoundPlayer extends JFrame
{
    private static final long serialVersionUID = 1L;

    public String code = "up up down down left right left right b a";
    static SoundPlayer soundPlayer;

    public static void main(String[] args)
    {
        soundPlayer = new SoundPlayer();
        soundPlayer.setVisible(true);
    }

    public SoundPlayer()
    {
        //Look and feel
        String lookAndFeel = UIManager.getSystemLookAndFeelClassName();
        try {
        UIManager.setLookAndFeel(lookAndFeel);
        } catch (ClassNotFoundException | InstantiationException| IllegalAccessException | UnsupportedLookAndFeelException e2) {e2.printStackTrace();}

        //Window Stuff
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(50, 50, 250, 80);
        setTitle("Sound Player Test");
        getContentPane().setLayout(null);

        //Components
        final JTextField typingArea = new JTextField(1);
        typingArea.setText("up up down down left right left right b a");
        typingArea.setBounds(10, 10, 100, 25);
        getContentPane().add(typingArea);

        final JLabel label = new JLabel("Now playing: ");
        label.setBounds(10, 40, 400, 25);
        label.setVisible(false);
        getContentPane().add(label);

        JButton button = new JButton("Check");
        button.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e) 
            {
                if(typingArea.getText().equals(code))
                {
                    setBounds(50, 50, 250, 110);
                    label.setVisible(true);
                    File file = new File("sound.wav");
                    playSound(file);
                }
            }
        });
        button.setBounds(125, 10, 100, 25);
        getContentPane().add(button);
    }

    public static void playSound(File file)
    {
        try
        {
            Clip clip = AudioSystem.getClip();
            clip.open(AudioSystem.getAudioInputStream(file));
            clip.start();
        }
        catch (Exception exc)
        {
            exc.printStackTrace(System.out);
        }
    }
}
4

1 回答 1

2

The problem is the line

File file = new File("sound.wav");

This is directly accessing the Filesystem. What you want instead is to load a resource from your JAR. This can be accomplished using the Classloader:

getClass().getResource("sound.wav");

You will then have a resource which provides the getInputStream as well, so you don't pass a File to the playSound, but the resource.

于 2013-10-15T16:13:06.377 回答