MediaPlayer pause doesnt work in android

↘锁芯ラ 提交于 2019-12-01 12:07:34

问题


I use the following code to pause the play of an audio file. but it doesn't pause. What is wrong with the code. Any suggesstion...

boolean play=false;
int flag=0;
mPlay.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {

            mPlayer = new MediaPlayer();
            if(play==false)
            {
                flag++;
                if(flag==1)
                {
                    playAudio();
                }

                else
                {
                    mPlayer.start();
                }
                mPlay.setText("Pause");
                play=true;
            }
            else if(play==true)
            {
                mPlayer.pause();
                mPlay.setText("Play");
                play=false;
            }
            mPlayer.setOnCompletionListener(new OnCompletionListener() {

                public void onCompletion(MediaPlayer mp) {
                    // TODO Auto-generated method stub
                    play=false;
                    flag=0;
                }
            });

回答1:


Problem lays here: mPlayer = new MediaPlayer(); You're initializing your player on every click, so what you're trying to pause is a completely new player that cannot be paused, cause it doesn't play. You must initialize the player outside of onClick method.



来源:https://stackoverflow.com/questions/6234838/mediaplayer-pause-doesnt-work-in-android

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