如何让MediaPlayer实现AB段复读功能

近日在做一个学习法语的小应用,被MP3AB段复读的功能困扰了很久,最后终于在网上找到一个解决方法,就是使用CountDownTimer让MediaPlayer只播放MP3的某个区段,轻松解决了AB段复读的功能。详细代码如下:
public void play(final String filePath) throws Exception {
	try {
		if (mMediaPlayer == null) {
			// 创建MediaPlayer对象并设置Listener
			mMediaPlayer = new MediaPlayer();
		} else {
			// 复用MediaPlayer对象
			mMediaPlayer.reset();
		}
		mMediaPlayer.setDataSource(filePath);
		mMediaPlayer.prepare();
		mMediaPlayer.setVolume(10.f, 1.0f);

		// 复读第10秒到第20秒这个区间的音频
		int startPos = 10000;
		int endPos = 20000;
		// Try to play three times
		repeatAToB(startPos, endPos, 3);

	} catch (Exception e) {
		e.printStackTrace();
	}
}

private void repeatAToB(final int startPos, final int endPos, final int repeatTimes)throws Exception {

		mMediaPlayer.seekTo(startPos);
		mMediaPlayer.start();
		CountDownTimer cntr_aCounter = new CountDownTimer(/* millisInFuture= */endPos - startPos, /* countDownInterval= */1000) {
			public void onTick(long millisUntilFinished) {
				// DO SOMETHING
			}

			public void onFinish() {
				// Code fire after finish
				if((repeatTimes - 1) > 0){
					try {
						repeatAToB(startPos, endPos, repeatTimes - 1);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}else{
					mMediaPlayer.stop();
				}
			}
		};
		cntr_aCounter.start();
	}


如果大家有更好的方案,欢迎拍砖!!

你可能感兴趣的:(android,mediaplayer)