0

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!

Dillon Burton
  • 363
  • 6
  • 16

1 Answers1

1

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.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Ok makes sense. Just to understand the functionality of FileInputStream in this situation: Say I were to place the executable jar in a folder called "player" and place another folder inside "player" called "media." Then I would make the program look for a folder called "media" outside of the jar file in a relative location. Would FileInputStream be applicable then? – Dillon Burton Dec 27 '12 at 01:01
  • 1
    @DillonBurton: No, because the MP3 resource *isn't a file*. It's contained within a jar file. `FileInputStream` reads data from a file on disk - not something embedded *within* a file. – Jon Skeet Dec 27 '12 at 01:02