dhsmith
dhsmith

Reputation: 250

music player "file not found" exception?

I'm try to add a soundtrack to a simple little java game, and I've researched how to do it to the extent that I have code that compiles. However, when I run it, I get a FileNotFound exception. I'm using Eclipse and my wav file is in the same directory as the .class files.

Here's my exception:

java.io.FileNotFoundException: bach.wav (No such file or directory)

And my code for the music player:

public static void play()
{
  try
  {
      Clip clip = AudioSystem.getClip();
      clip.open(AudioSystem.getAudioInputStream(new File("bach.wav")));
      clip.start();
  }
  catch (Exception exc)
  {
      exc.printStackTrace(System.out);
  }
 }

Upvotes: 0

Views: 1460

Answers (3)

Reimeus
Reimeus

Reputation: 159844

AudioSystem.getAudioInputStream has an overloaded method that takes a URL. This will use a buffered stream as required. As the .wav file is in the same location as the class file, you could use getResource:

AudioSystem.getAudioInputStream(getClass().getResource("bach.wav"));

As play is static you will need:

AudioSystem.getAudioInputStream(MyClass.class.getResource("bach.wav"));

Upvotes: 2

auroris
auroris

Reputation: 13

try change:

new File("bach.wav")

to:

new File("bach.wav").getAbsolutePath()

Upvotes: 0

schippi
schippi

Reputation: 1059

when you say new File("bach.wav") you have to put the file in the root folder of your project where the src and bin folders are

Upvotes: 1

Related Questions