MalformedURLException没有协议。怎么修?

时间:2014-07-05 11:52:19

标签: java audio malformedurlexception

所以我有这个代码:

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

 public class SoundTest {
     public static void main(String[] args) throws Exception {

    URL url = new URL("Sprites/Omni's Tones/New tones/bubblespawn_01.wav");
    AudioClip clip = Applet.newAudioClip(url);
    AudioClip clip2 = Applet.newAudioClip(url);
    clip.play();
    Thread.sleep(1000);
    clip2.loop();
    Thread.sleep(20000);
    clip2.stop();

    System.out.println("end");
     }
 }

出现错误:

 Exception in thread "main" java.net.MalformedURLException: no protocol: Sprites/Omni's Tones/New tones/bubblespawn_01.wav
at java.net.URL.<init>(URL.java:586)
at java.net.URL.<init>(URL.java:483)
at java.net.URL.<init>(URL.java:432)
at com.edu4java.minitennis7.SoundTest.main(SoundTest.java:10)

我该如何解决这个问题?谢谢!  我似乎需要在代码中添加更多行,

1 个答案:

答案 0 :(得分:3)

如果您在Applet中运行它,请尝试使用Applet#getCodeBase()Applet#getDocumentBase

URL url = getDocumentBase();

AudioClip audioClip = getAudioClip(url, "music/abc.wav")

如果它在独立应用程序中运行,请根据音乐文件位置选择一个:

// Read from same package
InputStream inputStream = getClass().getResourceAsStream("abc.wav");

// Read from music folder parallel to src in your project
File file = new File("music/abc.wav");

// Read from src/music folder
URL url = getClass().getResource("/music/abc.wav");

// Read from src/music folder
InputStream inputStream = getClass().getResourceAsStream("/music/abc.wav");