Skip to content Skip to sidebar Skip to footer

Android: Simple How To Stop Mediaplayer After Given Time

I am trying to play an mp3 file (with an onClickListener) and stop after 2 seconds. I tried the code below but it is not working. Could anyone please help? final MediaPlayer mpsoun

Solution 1:

Why are you calling stop() on mpfrog if you are playing audio with mpsound? You need to call the stop() function on the mpsound MediaPlayer. Also, you might want to add the @Override annotation to your onClick() method.

for the override...

sound.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mpsound.start();{
                    sleep(2000);
                    mpsound.stop();
                }
            }
        });

for a timer.....

Handlerhandler=newHandler(){
            @OverridepublicvoidhandleMessage(Message msg){
                mpsound.stop();
            }
        };

//Task for timer to execute when time expiresclassSleepTaskextendsTimerTask {
        @Overridepublicvoidrun(){
            handler.sendEmptyMessage(0);
        }
    }

//then in some other function...Timertimer=newTimer("timer",true);
timer.schedule(newSleepTask(),2000);

Solution 2:

You have to wait 2 seconds in different thread, for this case use your own created thread and wait there and stop player, or you can use CountDownTimer - very simple solution.

You can find same question aggregated here and here

In eclipse you can use autocomplete (ctrl + space by default) to fill automatically all inmplemented methods and @Overrides will already be there.

Post a Comment for "Android: Simple How To Stop Mediaplayer After Given Time"