如何同时启动两个媒体播放器(并让它同步播放)?

时间:2014-05-03 11:51:39

标签: android audio android-mediaplayer synchronous

例如:我有两个声音。持续40秒。我需要同时启动它们。这是我的方法:

private void startPlaying() {
        mPlayerDrums = MediaPlayer.create(this, mCurrentDrumResId);
        mPlayerDrums.setLooping(true);

        mPlayerTrack = MediaPlayer.create(this, mCurrentTrackResId);
        mPlayerTrack.setLooping(true);

        if (STATE == STATE_PLAY) {
            mPlayerDrums.start();
            mPlayerTrack.start();
        }

        setPlayersVolume(mSeekbar.getProgress());
    }

但有时他们不会同步播放。从日志(每400毫秒显示球员的位置):

05-03 14:47:01.190: V/wise(23335): drums pos 0 track pos 0
05-03 14:47:01.600: V/wise(23335): drums pos 93 track pos 0
05-03 14:47:02.001: V/wise(23335): drums pos 766 track pos 766
05-03 14:47:02.401: V/wise(23335): drums pos 1138 track pos 1138
05-03 14:47:02.801: V/wise(23335): drums pos 1556 track pos 1509
05-03 14:47:03.202: V/wise(23335): drums pos 1950 track pos 1950

1 个答案:

答案 0 :(得分:2)

您可以使用CyclingBarrier一次启动两个玩家。像这样的东西

    CyclicBarrier cyclicBarrier = new CyclingBarrier(2);
    public void onPrepared(MediaPlayer player) {
        new StartThread(player).start();
    }

    public class StartThread extends Thread {
        private MediaPlayer player;
        public StartThread(MediaPlayer player) {
            this.player = player;
        }
        @Override
        public void run(){
            cyclingBarrier.await();
            player.start();
        }
    }