Kris Kris - 5 months ago 12
Android Question

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

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:

package com.example.playword;

import java.io.IOException;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.widget.TextView;

public class PlayWord extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

final TextView tv = new TextView(this);

tv.setText("Playing...");
setContentView(tv);

final MediaPlayer mPlayer = MediaPlayer.create(this, R.raw.nicholas);

try {
mPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

mPlayer.seekTo(6889); //this is the start time
mPlayer.start();
//how can I end it at 7254 ms?
}
}

Answer

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.