Here is my Activity
:
public class MainActivity extends AppCompatActivity {
private SoundPool soundPool;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
soundPool = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
final int sound1 = soundPool.load(this, R.raw.whack, 1);
final int sound2 = soundPool.load(this, R.raw.miss, 1);
Button b1 = (Button) findViewById(R.id.b1);
Button b2 = (Button) findViewById(R.id.b2);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
playSound(sound1);
}
});
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
playSound(sound2);
}
});
}
private void playSound(int soundId) {
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
float volume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
soundPool.play(soundId, volume, volume, 1, 0, 1);
}
}
The problem is when I click on Button1, sound1 is played. Then when I click on Button1 again and again, nothing is played until I click on Button2. When I do that, sound2 is played. Then if I click on Button1, sound1 is played. Same scenario happens when I click on Button2 over and over. So what is the problem here?
We had the same problem and we found a workaround for this exact problem. Not the cleanest way to do it, but if it works, it ain't stupid!
It only works with a max number of streams set to 1. We play a silent sound at volume 0 just before playing our normal sound. Its priority is also 0. Yes it is that ugly!
This is Xamarin so it's C# code, but Java would be extremely similar.
Initialisation of our AudioService :
And when it comes to play a sound :