abalter
abalter

Reputation: 10383

Android sounds not playing after successive button clicks

I have a math game with multiple choice questions. I have a bell sound for a right answer and an oink sound for a wrong answer. There is a timed play mode which encourages the player to enter answers rapidly. The sounds play fine if answer buttons are pressed slowly. But if in quick succession, a sound fails to play.

The two sounds are each a fraction of a second long.

In the method that handles correct answers I have ting.start();, and in the method for wrong answers I have oink.start();

One thing I tried was to forcibly stop both sounds and then start only the one I want (see below) but then the sounds don't play at all! Any suggestions?

private void handleWrongAnswer(int chosenID)


{
//      Toast.makeText(getApplicationContext(), "Oops, try again.", Toast.LENGTH_SHORT).show();
        Button checked_button = (Button) findViewById(chosenID);
        checked_button.setEnabled(false);
        checked_button.setClickable(false);
        checked_button.setBackgroundColor(Color.rgb(255,100,100));

        score = score - 1.0/3.0;
        score_field.setText(String.format("%.2f", score));  

            ting.stop();
            oink.stop();
        oink.start();
    }

Upvotes: 3

Views: 361

Answers (1)

masmic
masmic

Reputation: 3564

Well I suppose that you are using Mediaplayer to play that sounds. If you want to play small audio clips and repeat them in small place of time you should use soundPool.

You should implement it this way:

private SoundPool soundPool;

@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  // Load the sound
  soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
  soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
    @Override
    public void onLoadComplete(SoundPool soundPool, int sampleId,
          int status) {
      loaded = true;
    }
  });
  soundID = soundPool.load(this, R.raw.sound1, 1);
}

And then when you want to use it:

// Getting the user sound settings
AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
float actualVolume = (float) audioManager
      .getStreamVolume(AudioManager.STREAM_MUSIC);
float maxVolume = (float) audioManager
      .getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float volume = actualVolume / maxVolume;
// Is the sound loaded already?
if (loaded) {
  soundPool.play(soundID, volume, volume, 1, 0, 1f);
}

Anyway you have a nice tutorial about this here.

Upvotes: 1

Related Questions