Search code examples
javaswingjfxtras

Java convert inputStream to URL


How can I convert an inputStream to a URL? Here is my code:

InputStream song1 = this.getClass().getClassLoader().getResourceAsStream("/songs/BrokenAngel.mp3");
URL song1Url = song1.toUrl(); //<- pseudo code
MediaLocator ml = new MediaLocator(song1Url);
Player p;
try {
    p = Manager.createPlayer(ml);
    p.start();
} catch (NoPlayerException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

Solution

  • Note that this approach requires the mp3 to be within your application's sub-directory called songs. You can also use relative pathing for the /songs/BrokenAngel.mp3 part (../../ or something like that. But it takes your applications directory as base!

        File appDir = new File(System.getProperty("user.dir"));
        URI uri = new URI(appDir.toURI()+"/songs/BrokenAngel.mp3");
        // just to check if the file exists
        File file = new File(uri);
        System.out.println(file.exists())
        URL song1Url = uri.toURL();