1

所以我有这个代码:

 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)

我该如何解决?谢谢!看来我需要在我的代码中添加更多行,

4

1 回答 1

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");
于 2014-07-05T11:55:03.023 回答