Android - 暂停执行直到声音播放

时间:2013-11-18 01:14:36

标签: java android audio for-loop

我正在为Android创建一个Simon Says应用。游戏有四个牌:红色,蓝色,绿色和黄色。当游戏开始时,程序选择1到4之间的随机数(对应于四种颜色)并将其存储在一个字符串中。每轮游戏都会为字符串添加一个新数字。然后程序应该是字符串中的第一个字符并播放一个独特的声音并使相应按钮的颜色变亮~1秒,然后再转到下一个字符。每次玩家正确输入模式时,它会在字符串中添加另一个数字。

我的问题是这样的:我找到了一些方法,可以在声音持续时间内使按钮变亮,但所有这些方法都会导致程序在声音完成播放所需的时间内执行整个for循环。这是我的代码:

case R.id.new_game_button:
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        combination += randomGenerator();

        for (int i=0; i < combination.length(); i++) {
            if (combination.charAt(i) == 49) {
                findViewById(R.id.red_button).setBackgroundResource(color.red_pressed);
                red_sound.start();

                red_sound.setOnCompletionListener(new OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        findViewById(R.id.red_button).setBackgroundResource(color.red);

                    }
                });
            }
        }
    }
    break;

我已经尝试过Thread.sleep(),OnCompletionListeners,postDelayed Handlers和CountDownTimers,但我无法让他们中的任何一个做我需要他们做的事情。我怎么能在声音播放时停止执行for循环呢?

1 个答案:

答案 0 :(得分:1)

您是否需要实际暂停执行代码?你可以跟踪你所在的数字,并在onCompletion()回调期间开始下一次迭代吗?

相关问题