How to Play .wav File with JButton?

与世无争的帅哥 提交于 2019-12-02 13:17:12

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

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