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:
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()
}
};