Hello,

I have an ImageButton that plays a sound whenever it is held down and
stops as soon as you let up.  To do this I register an onTouch handler
and operate on ACTION_DOWN and ACTION_UP MotionEvents.  The code is
below.  The idea is that when the ACTION_UP comes in I first call
stop() and then I re-prepare the sound so that it is all ready for the
next start() in a subsequent ACTION_DOWN.  I do this instead of start/
pause because I need the sound to start from the beginning each time
and the seekTo() call is asynch which seemed to complicated the
logic.  The problem I'm having is that every now and then if I'm
really "beating" on the button (i.e. clicking it rapidly and for
different durations) I will hit the illegal state exception.  The
debugger log shows that I am in MEDIA_PLAYER_PLAYBACK_COMPLETE (128)
when trying to call prepare().  As you can see below, I only try to
call prepare after I have called stop.  So this would imply that stop
is somehow either asynchronous or the two operations are being allowed
to happen in an overlapped fashion.

So two questions:  1) does anyone have an explanation for what I'm
seeing?   2) is there a better/cleaner way to do what I'm trying to do
in general?  This is my first android app so it's very possible I'm
missing the boat on something.

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Context appCtx = getApplicationContext();

// button init code removed

mSoundBeep = MediaPlayer.create(appCtx, R.raw.beep);

mImgBtnBeep.setOnTouchListener(new OnTouchListener() {
   public boolean onTouch(View v, MotionEvent event) {

   switch (event.getAction()) {
      case MotionEvent.ACTION_DOWN:
         mSoundBeep.start();
         break;

      case MotionEvent.ACTION_UP:
         if (mSoundBeep.isPlaying()) {
            mSoundBeep.stop();
         try {
               mSoundBeep.prepare();
            } catch (IllegalStateException e) {
               mSoundBeep.release();
               Context appCtx = getApplicationContext();
               mSoundBeep = MediaPlayer.create(appCtx, R.raw.beep);
            } catch (IOException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
            }
         }
         break;
   }

   return false;
   }
});

-- 
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en

Reply via email to