When developing Android, I want to press the button to play one of the various music, and then press the button again to play the next music.

Asked 2 years ago, Updated 2 years ago, 74 views

If you press the play button among a,b,c music, and if you press the confirmation button, music B is played I want to implement the function of playing c music when I press the confirmation button... I've done the transition from music a to music b... I don't know how to move on to musicPlease help me<

 Button btn1, btn2; //play button and confirm button
MediaPlayer mp,mp1,mp2;

protected void onCreate(Bundle savedInstanceState) {
btn1 = (Button)findViewById(R.id.button1);
btn1.setOnClickListener(listener);
btn2 = (Button)findViewById(R.id.button2);
btn2.setOnClickListener(listener);
mp = MediaPlayer.create(MainActivity.this, R.raw.music);
mp1 = MediaPlayer.create(MainActivity.this, R.raw.music1);
mp2 = MediaPlayer.create(MainActivity.this, R.raw.music2);
}

Button.OnClickListener listener = new Button.OnClickListener()
 {
public void onClick(View v)
{
 switch(v.getId()){
//When pressing the Play button
 case R.id.button1:
mp = MediaPlayer.create(MainActivity.this, R.raw.music);
//Play sound source through object
 mp.start();
 break;

//If you press the OK button
 case R.id.button2:
//The music stop that was played before
 mp.pause();
//Then import the sound source and recreate the object
mp = MediaPlayer.create(MainActivity.this, R.raw.music1);
 mp.start();
 break;
        }
  }  };

android software_development

2022-09-22 21:44

1 Answers

To summarize the question, I understood that I want to play 3 pieces of music in rotation every time I press the confirmation button, is that right?

I think we can solve the problem you want if you apply modular arithmetic and arrangement properly.

Next, if you modify the code based on the questioner's code, you can do it as follows.

The variables mp, mp1, mp2 are set to mp, and the sound source part is changed to an array.

private int songs[]; // sound source list
private int playing = -1; // sound source indicator currently playing

private ... onCreate(...) {
  // within the onCreate function
  songs = new int[3];
  songs[0] = R.raw.music;
  songs[1] = R.raw.music1;
  songs[2] = R.raw.music2;
}

For the playback button in the button section, do the following:

playing=0;
if( mp!=null ) {
    mp.stop(); // or pause
}
mp = MediaPlayer.create(MainActivity.this, songs[ playing ]);
mp.start();

The confirmation button is as follows:

playing = (playing+1)%songs.length; // Select first again when the end of the list is reached.
if( mp!=null ) {
    mp.stop(); // or pause
}
mp = MediaPlayer.create(MainActivity.this, songs[ playing ]);
mp.start();


2022-09-22 21:44

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.