javaaudiomalformedurlexception

MalformedURLException no protocol. How to fix?


So I have this Code:

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

An error Appears:

 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)

How do I fix this? Thank you! It seems that I need to add more lines to my code,


Solution

  • If you are running it inside the Applet then try with Applet#getCodeBase() and Applet#getDocumentBase

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

    If it's running in a standalone application then choose one based on music file location:

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