Android MediaPlayer实现单曲循环不卡顿

参考:

https://www.jianshu.com/p/99a84048a819

  • 创建第一个播放器,播放;
  • 同时创建第二个播放器,准备;
  • 第一个播放器播放完毕立马启动第二个;
  • 然后创建第三个播放器,准备;
  • 如此往复,直到用户停止…
private MediaPlayer mPlayer, mNextPlayer;
private int mPlayResId = R.raw.water;

public void testLoopPlayer() {
    mPlayer = MediaPlayer.create(this, mPlayResId);
    mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mediaPlayer) {
            mPlayer.start();
        }
    });
    createNextMediaPlayer();
}

private void createNextMediaPlayer() {
    mNextPlayer = MediaPlayer.create(this, mPlayResId);
    mPlayer.setNextMediaPlayer(mNextPlayer);
    mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            mp.release();

            mPlayer = mNextPlayer;

            createNextMediaPlayer();
        }
    });
}

已标记关键词 清除标记
MediaPlayer实现背景音乐播放时,播放一次时没错,循环播放时出错,望大神帮忙解决 public class FirstActivity extends AppCompatActivity{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent=new Intent(FirstActivity.this,MusicSever.class); startService(intent); } @Override protected void onDestroy(){ Toast.makeText(FirstActivity.this,"活动完", Toast.LENGTH_LONG).show(); Intent intent=new Intent(FirstActivity.this,MusicSever.class); stopService(intent); super.onDestroy(); } } 然后这是server类 public class MusicSever extends Service{ public MediaPlayer me; @Override public void onCreate(){ me=MediaPlayer.create(this,R.raw.yinyue1);//实例化播放器类 super.onCreate(); me.setLooping(true); } @Override public int onStartCommand(Intent intent,int flag,int startId){ me.start(); me.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { Toast.makeText(MusicSever.this,"在播放", Toast.LENGTH_LONG).show(); me.start(); } }); me.setOnErrorListener(new MediaPlayer.OnErrorListener() { @Override public boolean onError(MediaPlayer mp, int what, int extra) { Toast.makeText(MusicSever.this,"出错", Toast.LENGTH_LONG).show(); me.release(); return false; } }); return START_STICKY; // 在运行onStartCommand后service进程被kill后,并且没有新的intent传递给它 } @Override public void onDestroy(){ Toast.makeText(MusicSever.this,"播放完", Toast.LENGTH_LONG).show(); me.stop(); me.release(); super.onDestroy(); } @Override public IBinder onBind(Intent intent) { return null; } }
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页