Android: How to stop media (mp3) in playing when specific milliseconds come?

与世无争的帅哥 提交于 2019-11-28 08:34:25

The best approach is to use a Handler to time the stopping of the playback. Start the player and then use the Handler's postDelayed to schedule the execution of a Runnable that will stop the player. You should also start the player only after the initial seek completes. Something like this:

public class PlayWord extends Activity implements MediaPlayer.OnSeekCompleteListener {
    Handler mHandler;
    MediaPlayer mPlayer;
    int mStartTime = 6889;
    int mEndTime = 7254;
    final Runnable mStopAction = new Runnable() {
        @Override
        public void run() {
            mPlayer.stop();
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);    
        final TextView tv = new TextView(this);
        tv.setText("Playing...");
        setContentView(tv);
        mHandler = new Handler();
        mPlayer = MediaPlayer.create(this, R.raw.nicholas);
        mPlayer.setOnSeekCompleteListener(this);
        mPlayer.seekTo(mStartTime);
    }

    @Override
    public void onDestroy() {
        mPlayer.release();
    }

    @Override
    public void onSeekComplete (MediaPlayer mp) {
        mPlayer.start();
        mHandler.postDelayed(mStopAction, mEndTime - mStartTime);
    }
}

Note also that the MediaPlayer.create method you are using returns a MediaPlayer that has already been prepared and prepare should not be called again like you are doing in your code.on the screen. I also added a call to release() when the activity exits.

Also, if you want to update the UI when the seek completes, be aware that this method is usually called from a non-UI thread. You will have to use the handler to post any UI-related actions.

In Oncreate Method ,use the below 4 lines code:


     MediaPlayer mPlayer = MediaPlayer.create(this, R.raw.nicholas);
     mPlayer.start();
     mPlayer.seekTo(startTime);   
     updatePlayerPostion(); 


private Handler handler=new Handler(){

            @Override
            public void handleMessage(Message msg) {
                        // TODO Auto-generated method stub
                        super.handleMessage(msg);
                        updatePlayerPostion();
                }
            };
            updatePlayerPostion()
            {
               handler.removeCallbacks(r);
               if(player.getCurrentPosition==7254)

              player.stop();


            else
               handler.postDelayed(r, 1); //1 millisecond

            }
        Runnable r=new Runnable(){
        @Override
                public void run() {
                    // TODO Auto-generated method stub
                     updatePlayerPostion()
                }
        };
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!