您可以使用下面的代碼:
bt.setOnTouchListener(this);
@Override
public boolean onTouch(View arg0, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
System.out.println("touch");
mp.setLooping(true);
mp.start();
break;
case MotionEvent.ACTION_UP:
System.out.println("up");
mp.pause();
break;
}
return true;
}
我做了一些研究,發現Android的Mediaplayer
有彈無間斷的聲音,而循環的問題..
看到這個:Gapless Playback with android MediaPlayer
我也發現幾個解決方案:
- 使用OGG格式的聲音文件(https://en.wikipedia.org/wiki/.ogg)
- 可以使用的Soundpool它有一個循環和緩存設備的媒體播放(https://developer.android.com/reference/android/media/SoundPool.html)
你也可以使用以下類別:看看它是否工作..
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));
}
};
}
t Ø使用它只需調用mp.setLooping(true);
感謝您的回覆,循環工作,但我的聲源是1秒,我舉行1秒後,它有一個約0.1秒循環聲音的間隔。如何將間隔時間設置爲0? –
所以循環之間有一個GAP,你想把GAP時間設置爲0 .. – rafsanahmad007
是的,差距時間 –