2

This is the first time I've implemented sounds but I can't figure out where to actually place the sounds to play them. I am using Eclipse as my IDE and I've put my sounds in a folder called sounds.

The following code is what I've used to create one of the audioclip objects:

private final String background = "." + slash + "sounds" + slash + "background.wav";

main(....){
    try {
        backgroundClip = Applet.newAudioClip(new File(background).toURI().toURL());
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

I don't hear anything. When I remove the try/catch I get an error saying that it is unable to find the file. I placed my sound folder in both /src and /bin but neither can find it. where do I put it?

Bhesh Gurung
  • 50,430
  • 22
  • 93
  • 142
Jonathan
  • 479
  • 3
  • 8
  • 17
  • 1) `String background = "." + slash + ..` If the value of `slash` is `/` it is wrong. If the value is `System.getProperty("file.separator")` it should be called `separator` (or something similar). But `File` has constructors that can do all that for you. 2) Since Java 1.3, the J2SE has offered that `javax.sound.sampled` API. Use that instead of an `AudioClip`. – Andrew Thompson Dec 13 '11 at 03:44

2 Answers2

3

The base for your project is the level above the src folder. So using . will put you at your project folder.

Basically,

. = project_root

./src = default_package
./src/packagename = inside the package named "packagename"

./sounds/background.wav = a .wav file in the sounds folder, in the project_root

Using your current path, you need to put your .wav file in the sounds folder in the project_root.

The path will end up being project_root/sounds/background.wav.

Jon Egeland
  • 12,470
  • 8
  • 47
  • 62
  • What? isn't the "." refers to the current folder where the execution is going on? – Naved Dec 13 '11 at 03:34
  • yes. The execution occurs at `project_base`. I've spent days trying to figure this out before, and these were my results. – Jon Egeland Dec 13 '11 at 03:36
2

See this thread to understand why application resources should be obtained by URL obtained from getResource(), rather than a File converted to an URL.

Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • Concur. And with Java 7, it's even more important to use URL in your getResource(). I ran into a similar problem here: http://stackoverflow.com/questions/8091967/mark-reset-exception-during-getaudioinputstream – Phil Freihofner Feb 09 '12 at 04:34