tags:

views:

52

answers:

3

Hi…I searched the site and found another code that works correctly.

Now I have another problem:

When I create object from blow class and send the address of audio to its constructor, I have to send the complete address like:

“C:\Documents and Settings\TheHero\My Documents\NetBeansProjects\project1\src\project1\s1.wav”

But I want to use this code just with name of sound like : “s1.wav”.

I copied the sound into the src folder and then use “s1.wav” and the result was ”java.io.FileNotFoundException”.

If I use complete address of sound, when I run the program on another computer it does not work. I’m right?

//****************************

public class MusicPlayer {

private String filename;

public MusicPlayer(String filename) {
    this.filename = filename;
}
public void play() {
    try {
            InputStream in = new FileInputStream(filename);
            AudioStream as = new AudioStream(in);
            AudioPlayer.player.start(as); 

    } catch (IOException e) {
            e.printStackTrace();
    }          
}

//************************

I have the same problem with images. When I use these codes, I must use complete address of image

     File input = new File(imageName);
     image = ImageIO.read(input);

Please Someone help me!I really need these! Thank you all guys….

+6  A: 

You could use URLs in order to retrieving image and sound files. For example:

new ImageIcon(getClass().getResource("/com/foo/myimage.png")));

... will retrieve the image file from package com.foo assuming it is on your classpath somewhere (e.g. bundled in a jar file).

EDIT

For sound clips you take a similar approach; e.g. something like:

URL url = getClass().getResource("/com/foo/sound.wav");
AudioStream as = new AudioStream(url.openStream());
Adamski
Could u please explain more? What u've written is for images, what about sounds?Can I put sound in resource folder?
@Hamed - I've expanded my answer. Hope that helps.
Adamski
HAHAHA!!! I made it, it workes now!just send the relative address to constructor!
+1  A: 

FileInputStream(filename) is the key.

The filename can be absolute or relative. You seem to have two problems.

1). relative paths, s1.wav will be relative to the working directory of the running application, that's almost certainly not your src directory.

2). absolute paths on a different machine does

C:\Documents and Settings\TheHero\My Documents\NetBeansProjects\  etc.

actually exist on the remote machine?

djna
A: 

Instead of copying the file into the src, copy it into the bin folder. This is where execution happens.

If that doesnt work, you can call:

Properties sysProps = System.getProperties();

Then iterate through the Properties and look for one that's your current working directory. That's where you put your wav file.

Nick