问题描述
我几乎尝试了每种方法,但在循环10至15秒的单个音轨之间无法实现无间隙的音频播放.
I have tried almost every method but I've failed to achieve gapless audio playback between looping a single track with a duration of 10-15 seconds.
我尝试过并失败的步骤:
Steps I've tried and failed :
-
不同的音频文件格式
.mp3
.wav
.ogg
使用setLooping(true)
:
MediaPlayer mp1 = MediaPlayer.create(MainActivity.this, R.raw.track1);
mp1.setLooping(true);
mp1.start();
创建两个媒体播放器,并使用播放器一个接一个地循环播放setOnCompletionListener
相同的循环没有间隙.
Creating two mediaplayers and looping one after another usingsetOnCompletionListener
same failed to loop without gaps.
使用setNextMediaPlayer(nextmp)
的工作方式,但是只能进行两个循环.我们必须准备好并在前两个循环完成后重新开始.
Using setNextMediaPlayer(nextmp)
some how it works but only two loops is possible. We have to prepare and start again after the completion of previous two loops.
mp1.start();
mp1.setNextMediaPlayer(mp2);
更新:@Jeff Mixon回答的结果: Mediaplayer循环因Android错误而停止.杰夫·米克森(Jeff Mixon)可以正常工作,但此后只能循环10或20个循环,由于某些垃圾回收问题,媒体播放器立即停止保留日志,如下所示.我真的在这里呆了两年.预先感谢.
Update:Result of @Jeff Mixon answer:Mediaplayer looping stops with an error Android.Jeff Mixon works fine but only for 10 or 20 loops after that, due to some garbage collection issue the Mediaplayers stops immediately leaving the logs as posted below. I'm really kind of stuck here for 2 years. Thanks in advance.
E/MediaPlayer(24311): error (1, -38)
E/MediaPlayer(23256): Error(1,-1007)
E/MediaPlayer(23546): Error (1,-2147483648)
推荐答案
根据我所做的测试,该解决方案可以正常工作,在150个循环中播放13秒的160 kbps MP3,没有任何问题:
From the test that I have done, this solution works fine, over 150 loops with a 13 seconds 160 kbps MP3 without any problem:
public class LoopMediaPlayer {
public static final String TAG = LoopMediaPlayer.class.getSimpleName();
private Context mContext = null;
private int mResId = 0;
private int mCounter = 1;
private MediaPlayer mCurrentPlayer = null;
private MediaPlayer mNextPlayer = null;
public static LoopMediaPlayer create(Context context, int resId) {
return new LoopMediaPlayer(context, resId);
}
private LoopMediaPlayer(Context context, int resId) {
mContext = context;
mResId = resId;
mCurrentPlayer = MediaPlayer.create(mContext, mResId);
mCurrentPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mediaPlayer) {
mCurrentPlayer.start();
}
});
createNextMediaPlayer();
}
private void createNextMediaPlayer() {
mNextPlayer = MediaPlayer.create(mContext, mResId);
mCurrentPlayer.setNextMediaPlayer(mNextPlayer);
mCurrentPlayer.setOnCompletionListener(onCompletionListener);
}
private MediaPlayer.OnCompletionListener onCompletionListener = new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.release();
mCurrentPlayer = mNextPlayer;
createNextMediaPlayer();
Log.d(TAG, String.format("Loop #%d", ++mCounter));
}
};
}
要使用LoopMediaPlayer
,您可以致电:
LoopMediaPlayer.create(context, R.raw.sample);
这篇关于到目前为止,无法在Android上实现无间隙音频循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!