Playing multiple songs with MediaPlayer at the same time: only one is really playing

前端 未结 5 1909
甜味超标
甜味超标 2021-01-02 04:44

I need help with playing multiple audio tracks at the same time in Android.

I am supposed to play three audio tracks at the exact same

5条回答
  •  悲哀的现实
    2021-01-02 05:04

    I achieved what you're looking for using a CyclicBarrier instance and an inner class implementation.

    Example:

    public enum MP_COMMAND {
        START,
        STOP,
        PAUSE
    }
    
    /**
     * Uses threads to execute synced commands for the current video media player and 
     * background music player in tandem.
     */
    public void syncedCommand(MediaPlayer player1, MediaPlayer player2, MP_COMMAND command) {
        final CyclicBarrier commandBarrier = new CyclicBarrier(2);
        new Thread(new SyncedCommandService(commandBarrier, player1, command)).start();
        new Thread(new SyncedCommandService(commandBarrier, player2, command)).start();
    }
    
    /**
     * Inner class that starts a given media player synchronously
     * with other threads utilizing SyncedStartService
     */
    private class SyncedCommandService implements Runnable {
        private final CyclicBarrier              mCommandBarrier;
        private       MediaPlayerTest.MP_COMMAND mCommand;
        private       MediaPlayer                mMediaPlayer;
    
        public SyncedCommandService(CyclicBarrier barrier, MediaPlayer player, MediaPlayerTest.MP_COMMAND command) {
            mCommandBarrier = barrier;
            mMediaPlayer = player;
            mCommand = command;
        }
    
        @Override public void run() {
            try {
                mCommandBarrier.await();
            } catch (InterruptedException | BrokenBarrierException e) {
                e.printStackTrace();
            }
    
            switch (mCommand) {
                case START:
                    mMediaPlayer.start();
                    break;
    
                case STOP:
                    mMediaPlayer.stop();
                    break;
    
                case PAUSE:
                    mMediaPlayer.pause();
                    break;
    
                default:
                    break;
            }
        }
    }
    

    You'd utilize it like so:

    syncedCommand(mCurrentVideoPlayer, mBackgroundMusic, MP_COMMAND.START);
    

    If you had the requirement that it be usable for any number of media players, you could easily implement it - my requirements just call for two.

    I realize this question is old, but this page is where I found myself while searching for a solution, so I hope this helps anyone stuck on this issue in the future.

提交回复
热议问题