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

后端 未结 2 1345
醉酒成梦
醉酒成梦 2020-12-09 12:14

I have an mp3 file and I want to play a specific word in it. I have a start time (6889 ms) and end time (7254 ms).

I have these codes:

2条回答
  •  被撕碎了的回忆
    2020-12-09 12:31

    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.

提交回复
热议问题