Here’s what I am trying to achieve: When user presses “Button A”, a 30 seconds “sound.mp3” starts playing over and over for 200 seconds and then stops. “Button B” plays the same sound for 400 seconds and stops.
Here’s my last attempt, using CountDownTimer (not sure if that’s the best approach or even possible):
public class MyClass extends Activity {
MediaPlayer player_test;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_rain);
my_player();
}
public void my_player(){
player_test = MediaPlayer.create(getApplicationContext(), R.raw.mysound);
player_test.setLooping(true);
player_test.start();
}
public void onCompletion(MediaPlayer player_test) {
player_test.stop();
player_test.release();
}
});
public void player_OnClick(View v) {
switch (v.getId()) {
case R.id.button_a:
new CountDownTimer(200000, 1000) {
public void onTick(long millisUntilFinished) {
player_test.start();
}
public void onFinish() {
player_test.pause();
}
}.start();
break;
case R.id.button_b:
new CountDownTimer(400000, 1000) {
public void onTick(long millisUntilFinished) {
player_test.start();
}
public void onFinish() {
player_test.pause(); }
}.start();
break;
}
}
Thank you for your answers.
It’s a good approach. However, you should fix some points in your code:
player_test.start()in yourmy_player()method, it causes the player to start playing when your activity is created. You should only instantiate theplayer_testobject in that method.player_test.start()in every tick of theCountDownTimer. You only need to call it one time to start playing.Call
player_test.start()whenever any of the buttons A or B is clicked.