Search code examples
javaaudionetbeansclassloaderjlayer

File Input Stream working fine in compiler, but not working after build


I am trying to play an mp3 file using a neat library I just discovered (JLayer) and it works fine when compiled (in Netbeans) with this code:

ClassLoader cl = this.getClass().getClassLoader();
url = cl.getResource("music/45.mp3");
pin = new FileInputStream(url.getFile());
p = new Player(pin);
p.play();

I built my project and attempted to run the executable jar. I extended JFrame so I could visually see that my program was running. The Frame appears when executed, but no sound. I though that using a class loader would fix this issue, but no luck. Help would be greatly appreciated!


Solution

  • Don't use FileInputStream when you've got a resource which may be in a jar file - use ClassLoader.gerResourceAsStream or Class.getResourceAsStream. That's what they're there for. You haven't got a separate file on disk, so it's pointless trying to use FileInputStream with it.

    (Of course, you may also find that you're not making the resource available properly - but that's a separate issue.)

    So just use:

    Player p = new Player(getClass().getResourceAsStream("/music/45.mp3"));
    p.play();
    

    (From your code, it looks like you're declaring your variables much earlier than you need to - or possibly even declaring them as fields when they should logically just be local variables. It's worth keeping an eye on that. Make sure you only use fields when you really want to indicate some state of the class or instance, and declare local variables as late as you can - ideally at the point of initialization.)