连续按钮点击后,Android无法播放

时间:2014-06-19 07:52:02

标签: android android-mediaplayer

我有一个有多项选择题的数学游戏。我有正确答案的铃声和错误答案的o声。有一种定时播放模式,鼓励玩家快速输入答案。如果慢慢按下接听按钮,声音会很好。但如果连续播放,声音就无法播放。

这两个声音都是一秒钟的一小部分。

在处理正确答案的方法中我有ting.start();,在错误答案的方法中我有oink.start();

我尝试过的一件事就是强行停止两种声音,然后只启动我想要的声音(见下文)但声音根本不播放!有什么建议吗?

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();
    }

1 个答案:

答案 0 :(得分:1)

好吧,我想你正在使用Mediaplayer来播放这些声音。如果你想播放小的音频片段并在很短的时间内重复播放,你应该使用soundPool。

你应该这样实现:

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);
}

然后当你想要使用它时:

// 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);
}

无论如何,你有一个很好的关于这个here的教程。