Vasant Raval
Vasant Raval

Reputation: 303

How to pause one audio file when another starts playing and viseversa

I have two audio files. I want that if one audio is playing and the user clicks the second-one, the first audio will pause (while maintaining the progress and also continue where it is left when played again) and start the second audio and vice versa.

How can I achieve this functionality?

I'm new to Android media

Code

The onClick is in the last if you want to jump directly there also the onClick is implemented in XML , if you want to view the XML please tell me I will update it.

public class MainActivity extends AppCompatActivity {
    MediaPlayer player1, player2;
    SeekBar seekBar1, seekBar2;
    TextView currentTime1, currentTime2;
    TextView remainingTime1, remainingTime2;
    ImageView play1, play2;
    int totalTime1, totalTime2;

    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // PlayButton    *  The onClick is in the last if you want to jump directly there  *

        play1 = findViewById(R.id.playbtn);
        play2 = findViewById(R.id.playbtn2);

        // TimeLables

        currentTime1 = findViewById(R.id.currentTime1);
        currentTime2 = findViewById(R.id.currentTime2);
        remainingTime1 = findViewById(R.id.totalTime1);
        remainingTime2 = findViewById(R.id.totalTime2);

        // MediaPlayer

        player1 = MediaPlayer.create(this, R.raw.dog_howl);
        player2 = MediaPlayer.create(this, R.raw.dog_bark);
        player1.setLooping(false);
        player1.seekTo(0);
        totalTime1 = player1.getDuration();
        player2.setLooping(false);
        player2.seekTo(0);
        totalTime2 = player2.getDuration();


        //SeekBar *Progress*

        seekBar1 = findViewById(R.id.seekbar1);
        seekBar2 = findViewById(R.id.seekbar2);
        seekBar1.setMax(totalTime1);
        seekBar2.setMax(totalTime2);

        seekBar1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                player1.seekTo(progress);
                seekBar1.setProgress(progress);

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {


            }
        });
        seekBar2.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                player2.seekTo(i);
                seekBar2.setProgress(i);


            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {


            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {


            }
        });


        new Thread(() -> {
            while (player1 != null) {
                try {
                    Message msg = new Message();
                    msg.what = player1.getCurrentPosition();
                    handler1.sendMessage(msg);
                    Thread.sleep(1000000000);
                } catch (InterruptedException ignored) {

                }
            }
        }).start();

        new Thread(() -> {
            while (player2 != null) {
                try {
                    Message msg = new Message();
                    msg.what = player2.getCurrentPosition();
                    handler2.sendMessage(msg);
                    Thread.sleep(1000000000);
                } catch (InterruptedException ignored) {

                }
            }
        }).start();


        // Admob Banner Ad

        MobileAds.initialize(this, initializationStatus -> {
        });

        AdView mAdView = findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);

    }

    @SuppressLint("HandlerLeak")
    private final Handler handler1 = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            int currentPosition1 = msg.what;
            //update seekbar
            seekBar1.setProgress(currentPosition1);
            currentTime1.setText(createTimerLable1(seekBar1.getProgress()));
            String totTime1 = createTimerLable1(player1.getDuration());
            remainingTime1.setText(totTime1);

        }
    };
    @SuppressLint("HandlerLeak")
    private final Handler handler2 = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            int currentPosition2 = msg.what;
            //update seekbar
            seekBar2.setProgress(currentPosition2);
            currentTime2.setText(createTimerLable1(seekBar2.getProgress()));
            String totTime2 = createTimerLable2(player2.getDuration());
            remainingTime2.setText(totTime2);

        }
    };

    public String createTimerLable1(int duration) {
        String timerLabel = "";
        int min = duration / 1000 / 60;
        int sec = duration / 1000 % 60;
        timerLabel += min + ":";
        if (sec < 10) timerLabel += "0";
        timerLabel += sec;
        return timerLabel;


    }

    public String createTimerLable2(int duration) {
        String timerLabel = "";
        int min = duration / 1000 / 60;
        int sec = duration / 1000 % 60;
        timerLabel += min + ":";
        if (sec < 10) timerLabel += "0";
        timerLabel += sec;
        return timerLabel;


    }

    public void playBtnClick1(View view) {
        if (!player1.isPlaying()) {
            // Stoping
            player1.start();
            play1.setImageResource(R.drawable.ic_baseline_pause_circle_filled_24);
        } else {
            // Playing
            player1.pause();
            play1.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
        }

    }

    public void playBtnClick2(View view) {
        if (!player2.isPlaying()) {
            // Stoping
            player2.start();
            play2.setImageResource(R.drawable.ic_baseline_pause_circle_filled_24);
        } else {
            // Playing
            player2.pause();
            play2.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
        }

    }

}


// TimeLable issue  * please read the comments for whats happening here *

public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                player2.seekTo(i);
                seekBar2.setProgress(i);
                currentTime2.setText(createTimerLable2(i));


            }

Upvotes: 2

Views: 233

Answers (2)

Ehsan Pagheh
Ehsan Pagheh

Reputation: 81

if I got you what you mean your solution is really easy. when you want to play new one you could stop the Previous.

just use these two method:

    player1.start();
    player2.stop();

so is player2 starting stop the player1.

Upvotes: 1

Bhavik Kalsariya
Bhavik Kalsariya

Reputation: 217

Add this Code:-

public void playBtnClick1(View view) {

    if (player2.isPlaying()) {
        player2.pause();
        play2.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
    }
    
    if (!player1.isPlaying()) {
        // Stoping
        player1.start();
        play1.setImageResource(R.drawable.ic_baseline_pause_circle_filled_24);
    } else {
        // Playing
        player1.pause();
        play1.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
    }

}

public void playBtnClick2(View view) {

    if (player1.isPlaying()) {
        player1.pause();
        play1.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
    }
    
    if (!player2.isPlaying()) {
        // Stoping
        player2.start();
        play2.setImageResource(R.drawable.ic_baseline_pause_circle_filled_24);
    } else {
        // Playing
        player2.pause();
        play2.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
    }

}

Upvotes: 0

Related Questions