0

I am attempting to play a sound using a MediaPlayer object, but I cannot seem to get it to work despite my best efforts. The sound simply refuses to play.

It's a short sound, that is supposed to be played when the screen is touched, meaning it will have to be repeated many times without too much delay. Knowing this I followed the state diagram, http://developer.android.com/reference/android/media/MediaPlayer.html. I can't seem to see what exactly is wrong with my sequencing of method calls.

MediaPlayer mp = MediaPlayer.create(this.getContext(), R.raw.select2);
try {
    mp.prepare();
    mp.start();                 
    Log.e("debug","sound played");
    }
catch(Exception e) {}
mp.stop();
2
  • No need of call prepare method.....In the first line it is automatically prepared and you have to start player in onPrepare listener... Dec 22, 2011 at 11:43
  • Thanks! I didn't know about the OnPreparedListener class. It's working now.
    – rolledback
    Dec 22, 2011 at 17:26

2 Answers 2

0

You call prepare() on the mediaplayer, but the create() call you use prepares the player automatically, this causes an IllegalStateException when you try to call prepare() again, and you are sent to your catch() (you would have noticed this if you handled the exception in some way, i.e. printing the stack trace).

0
MediaPlayer player = MediaPlayer.create(this.getContext(), R.raw.select2);

we configure the music player by setting some of its properties as shown below

player.setWakeMode(getApplicationContext()PowerManager.PARTIAL_WAKE_LOCK);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setOnPreparedListener(this);
player.setOnCompletionListener(this);
player.setOnErrorListener(this);
try {
   player.prepare();
   player.start();                 
   Log.e("debug","sound played");
}  catch(Exception e) {}
  player.stop();
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.