Reputation: 3
When you click the button it adds 5 to a sum and makes a sound. The problem is that when you click it repeatedly, it adds 5 but the sound does not overlap.
Please see code below:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_basic_2);
final MediaPlayer plussound = MediaPlayer.create(basic_2.this, R.raw.plus);
Button plus5b = (Button)findViewById(R.id.button);
plus5b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
plussound.start();
for (int i = 1; i <= 5; i++) {
counterValue++;
}
counterdown.setText(String.valueOf(counterValue));
}
});
}
Upvotes: 0
Views: 620
Reputation: 9756
One MediaPlayer
can only play one sound at a time, so you need to create a new MediaPlayer
for each sound, so create it inside the onClick
method. Also make sure to get rid of it after the sound is played (using a MediaPlayer.OnCompletionListener
) to avoid having memory issues.
Button plus5b = (Button)findViewById(R.id.button);
plus5b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MediaPlayer mediaPlayer = MediaPlayer.create(basic_2.this, R.raw.plus);
// Adding an onCompletionListener to ensure the MediaPlayer releases the memory after playing
plussound.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.release();
mediaPlayer = null;
}
});
mediaPlayer.start();
for (int i = 1; i <= 5; i++) {
counterValue++;
}
counterdown.setText(String.valueOf(counterValue));
}
});
Upvotes: 3
Reputation: 2401
If you wanted to have the sound overlay you would need the code to be the following:
Button plus5b = (Button)findViewById(R.id.button);
plus5b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
for (int i = 1; i <= 5; i++) {
counterValue++;
}
counterdown.setText(String.valueOf(counterValue));
plussound.start();
}
});
The reason the sound method needs to be inside the for loop and not outside of it is because when it is outside and the button is clicked it only goes off once because the action is not repeated every time the user clicks it.
Upvotes: 0