0

I'm trying to do the equivalent of this line of code, except substituting a small mp3 file for the system beep:

Toolkit.getDefaultToolkit().beep();

I have an mp3 file that has a little sound effect that I want to play. Is this a relatively easy thing to do? Can somebody show me the code to do this?

JimmyPena
  • 8,694
  • 6
  • 43
  • 64
AndroidDev
  • 20,466
  • 42
  • 148
  • 239
  • So searching Java mp3 on Google didn't give you any hits? Really? Heck just searching this site gave me more than enough information to answer this in seconds. e.g. [just one Google hit](http://stackoverflow.com/questions/657921/how-to-stream-mp3-using-pure-java) – Hovercraft Full Of Eels Jun 19 '12 at 01:16
  • I didn't say that I didn't get any hits. Just nothing that I was able to use simply. – AndroidDev Jun 19 '12 at 01:43
  • And maybe because it doesn't exist. There is no single simple line of code obviously, and you'll have to use a library such as is described in the links. It's not that hard to do. Next time, though please ask a better question and tell us what you've found and why it's not working for you. – Hovercraft Full Of Eels Jun 19 '12 at 01:46
  • 4
    Are you having a bad day? Get some sleep. – AndroidDev Jun 19 '12 at 01:55
  • The source shown on the [Java Sound info. page](http://stackoverflow.com/tags/javasound/info) that uses a `Clip`, can play short MP3 samples. Add the mp3plugin.jar of the JMF to the run-time class-path, for MP3 support. – Andrew Thompson Jun 19 '12 at 14:33

1 Answers1

5

You could use MediaPlayer to play the sound. Here is what I usually use for all my audio.

public class APP extends Activity {

//ADD THIS LINE AND IMPORT MediaPlayer
MediaPlayer btnClick;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//ADD THIS LINE TO YOUR onCreate METHOD AFTER YOU SET THE CONTENT VIEW
btnClick = MediaPlayer.create(this, R.raw.button_click);
    }
}

This sets up your audio and what it should play. It will play your sound until it is finished. Then add this line to wherever you want the sound to play:

btnClick.start();

If you want it to loop (a soundtrack or song), add this:

btnClick.setLooping(true);

Once you are finished with the soundtrack that you looped or you are finished with the application, add this to stop the audio:

btnClick.stop();

OR

btnClick.release();

So technically you would be adding 2 lines for the MediaPlayer itself, 1 line to start it, and 1 line to end it (optional but best for good programming habits and practices).

I hope this thoroughly answers your question. Cheers!

Kurty
  • 475
  • 2
  • 16