Android: Simple how to stop mediaplayer after given time

元气小坏坏 提交于 2019-12-24 00:48:36

问题


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 mpsound = MediaPlayer.create(this, R.raw.media_player_sound);

ImageView sound = (ImageView) findViewById(R.id.button);

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

回答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.....

Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg){
                mpsound.stop();
            }
        };

//Task for timer to execute when time expires
    class SleepTask extends TimerTask {
        @Override
        public void run(){
            handler.sendEmptyMessage(0);
        }
    }

//then in some other function...
Timer timer = new Timer("timer",true);
timer.schedule(new SleepTask(),2000);



回答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.



来源:https://stackoverflow.com/questions/11550789/android-simple-how-to-stop-mediaplayer-after-given-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!