简体   繁体   中英

How to Play .wav File with JButton?

So recently, I have been trying to make my own Mario game (for myself, possibly to show my other friends). Games include buttons. When I click on a button in other games, it plays a sound. I would love to add that feature to my game. The problem is, it doesn't play. My source code is:

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

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class JButtonClick {

    JButton test = new JButton("Click Me!");
    JPanel panel = new JPanel();

    public void playSound(String soundName)
     {
       try 
       {
        AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File(soundName).getAbsoluteFile());
        Clip clip = AudioSystem.getClip();
        clip.open(audioInputStream);
        clip.start();
       }
       catch(Exception ex)
       {
         System.out.println("Error with playing sound.");
         ex.printStackTrace( );
       }
     }


    public JButtonClick() {
        JFrame frame = new JFrame("Button-Click test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.pack();
        frame.add(panel);
        frame.setSize(800, 600);
        frame.setResizable(true);
        frame.setVisible(true);

        panel.add(test);

        test.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e)
            {
             playSound("JButton.wav");
            }
        });
    }
    public static void main(String[] args) {
        new JButtonClick();
    }
}

My .wav file is in the same package as this class. But instead of it playing the sound I want, it just says this:

java.io.FileNotFoundException: C:\Users\diego\workspace\Super Mario Bros 1\JButton.wav (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at com.sun.media.sound.WaveFloatFileReader.getAudioInputStream(Unknown Source)
at javax.sound.sampled.AudioSystem.getAudioInputStream(Unknown Source)
at JButtonClick.playSound(JButtonClick.java:21)
at JButtonClick$1.actionPerformed(JButtonClick.java:49)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

What am I doing wrong?!

Here is the problem due to placement of your .wav file.

As per your question your have placed it in the same package as this class that's why you are getting FileNotFoundException .

Let me explain you how new File(pathname) works:

Javadoc about File says:

A pathname, whether abstract or in string form, may be either absolute or relative. An absolute pathname is complete in that no other information is required in order to locate the file that it denotes. A relative pathname, in contrast, must be interpreted in terms of information taken from some other pathname. By default the classes in the java.io package always resolve relative pathnames against the current user directory.

  • It you are running this application in eclipse then place .wav file directly in the project (outside src folder) as shown below:

     AudioSystem.getAudioInputStream(new File("Jbutton.wav")); 

在此处输入图片说明

  • You can try also by placing it in resource folder.

     AudioSystem.getAudioInputStream(new File("resources/Jbutton.wav")); 

快照2

custom sounds play...using NetBeans..
First of all import some package or class name like this

   import java.applet.Applet;
   import java.applet.AudioClip;
   import java.net.URL;

Not working because generate Error on java.lang.NullPointerException

URL url = getClass().getResource("\\dbmsystem\\src\\sound\\Your_sound_name.wav");

URL url = getClass().getResource("G:\\zala\\dbmsystem\\src\\sound\\Your_sound_name.wav");

But Proper Working like this

URL url = getClass().getResource("/sound/Your_sound_name.wav");    
AudioClip clip = Applet.newAudioClip(url);
clip.play();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM