• 0

[JAVA] inserting a sound clip into a JFrame... help!


Question

Hey all,

I am building a frogger game, which consists of a frog having to pass rivers and roads...

I need to add a sound theme for it that loops through the game...

I am not able to insert the .mp3 file..

I tried several tutorials but didnt seem to work for me, or the solution was so complex... :no:

any help?

thanks in advance ;)

Link to comment
Share on other sites

1 answer to this question

Recommended Posts

  • 0

Well, you have two real choices in a case like this. As default, java doesn't support much in the way of audio or video. The best way (the way Sun would tell you to do it) would be to use the JMF (Java Media Framework), which lets you pick the classes you need, for the jobs you need done and have them packaged with your code. I haven't used this much so I can't really detail it too much.

There is however another way to play audio in java. The only issue is that it only supports .au files (and .wav files too I believe), and that it doesn't natively support a loop function (since you want to loop your theme). When I wanted to loop audio using it, I created a javax.swing.Timer with a time set (in milliseconds) to the length of the song, after which it called a method which played the song again. It's not the best approach but it worked (and I wasn't allowed to package JMF files with my project so I had no other choice). Using this will also throw a warning saying that support for this may later be removed.

So, if you're interested, here's the code I use; Firstly, you have to import sun.audio.*; (You can see that that's not a normal package to important)

Then you have to create a method similar to the one I used;

public static void playAudio(String filename)

{

InputStream in = null;

AudioStream as = null;

try

{

//create audio data source

in = new FileInputStream(filename);

}

catch(FileNotFoundException fnfe)

{

System.out.println("The audio file was not found");

}

try

{

//create audio stream from file stream

as = new AudioStream(in);

}

catch(IOException ie)

{

System.out.println("Audio stream could not be created");

}

AudioPlayer.player.start(as);

}

If you don't like that approach or it doesn't suit your needs, the only other option is the JMF I think.

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.