简体   繁体   中英

AudioClip Will Not Play, File Path Incorrect?

I created a quick small applet to play an audio clip, but as of right now, no dice. I have no idea why, and the path to the file is correct. What am I doing wrong? Here is the code

import javax.swing.JApplet;
import java.applet.Applet;
import java.applet.AudioClip;
import java.net.URL;

public class PlayAudioClippls extends JApplet {
private URL soundToPlay = getClass().getResource("C:\\Users\\Brian Murphy\\workspace\\FlagsSOUND\\anthem_mid files\\anthem6.mid");
private AudioClip AC = Applet.newAudioClip(soundToPlay);

public void init()
{
AC.play();  
}

}              

Here is the exception list

java.lang.NullPointerException
at sun.applet.AppletAudioClip.<init>(Unknown Source)
at java.applet.Applet.newAudioClip(Unknown Source)
at PlayAudioClippls.<init>(PlayAudioClippls.java:10)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
at sun.applet.AppletPanel.createApplet(Unknown Source)
at sun.applet.AppletPanel.runLoader(Unknown Source)
at sun.applet.AppletPanel.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

[...] the path to the file is correct. What am I doing wrong?

The path to the file is not correct, in that you are giving a path relative to the machine's file system, whereas Class.getResource() [ordinarily] wants a path relative to one of the directories in the applet's classpath. You get a NullPointerException because your getResource() call returns null on account of that problem.

Note well: it's only indirectly a matter of the location of the file. It is primarily a question of how the path to it is expressed. You may put the file in a directory that is on the applet's classpath (perhaps C:\\Users\\Brian Murphy\\workspace\\PlayAudioClippls\\bin ) or in a subdirectory somewhere beneath such a directory. The former is slightly easier than the latter. In that case, you would want this:

private URL soundToPlay = getClass().getResource("/anthem6.mid");

"Relative to a directory in the class path" means you specify only the part of the path that follows the relevant class path directory. That can include subdirectories if you like, so that the applet's resources don't have to all appear in the root of its jar.

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