如何在简单的Android游戏中立即停止播放所有声音和动画?

时间:2015-09-08 16:29:28

标签: java android

我正在阅读John Horton撰写的“安装Android游戏学习Java”一书。

Link to book Java by Building Android Games by John Horton

这是一本非常好的书,我正在通过它输入游戏。我有一个记忆游戏工作,从一个序列中的四个按钮之一播放声音,逐渐增加长度(每回合一个)。

我的代码存在的问题是,按钮会震动并发出与用户同时出现的声音。

如何添加延迟以阻止一次发生的所有事情?第一个序列只有一个按钮,因此它只会振动并发出一个按钮 - 所以没有混淆。

屏幕截图是序列中每个按钮振动的样子。

我试过了:

CalendarItem

对于每个按钮/案例陈述 - 但它不起作用。

Memory Game - Game Screen with buttons

     ...
     case 1:
     //play a sound
     button1.startAnimation(wobble);
     soundPool.play(sample1, 1, 1, 0, 0, 1);

try {
 wait(1000);
}
catch(Exception e){
System.out.println("Unable to wait");
}
    break;
...

我已尝试过您的建议,如下所示,但未达到预期效果。我甚至得到了消息"应用程序可能在其主线程上做了太多工作"

package com.packtpub.memorygame;

import android.app.Activity;
import android.content.SharedPreferences;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.util.Arrays;
import java.util.Random;


public class GameActivity extends Activity implements View.OnClickListener {

    //phase 5 - our animation object
    Animation wobble;

    //prepare objects and sound references

    //initalize sound variables
    private SoundPool soundPool;
    int sample1 = -1;
    int sample2 = -1;
    int sample3 = -1;
    int sample4 = -1;

    //for our UI
    TextView textScore;
    TextView textDifficutly;
    TextView textWatchGo;

    Button button1;
    Button button2;
    Button button3;
    Button button4;
    Button buttonReplay;

    //Some variables for our Thread
    int difficultyLevel = 3;
    //An Array to hold the randomly generated sequence
    int[] sequenceToCopy = new int[100];

    private Handler myHandler;
    //Are we playing a sequence at the moment?
    boolean playSequence = false;
    //And which element of the sequence are we on?
    int elementToPlay = 0;

    //For checking the players answer
    int playerResponses;
    int playerScore;
    boolean isResponding;

    //for our hiscore (Phase 4)
    SharedPreferences prefs;
    SharedPreferences.Editor editor;
    String dataName = "MyData";
    String intName = "MyString";
    int defaultInt = 0;
    int hiScore;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game);

        //phase 5 animation
        wobble = AnimationUtils.loadAnimation(this, R.anim.wobble);

        //phae 4
        //initialize our two SharedPreferences objects
        prefs = getSharedPreferences(dataName, MODE_PRIVATE);
        editor = prefs.edit();
        hiScore = prefs.getInt(intName, defaultInt);


        soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);

        try {

            //Create objects of the 2 required classes
            AssetManager assetManager = getAssets();
            AssetFileDescriptor descriptor;

            //Create our three fx in memory ready for use
            descriptor = assetManager.openFd("sample1.ogg");
            sample1 = soundPool.load(descriptor, 0);

            descriptor = assetManager.openFd("sample2.ogg");
            sample2 = soundPool.load(descriptor, 0);

            descriptor = assetManager.openFd("sample3.ogg");
            sample3 = soundPool.load(descriptor, 0);

            descriptor = assetManager.openFd("sample4.ogg");
            sample4 = soundPool.load(descriptor, 0);

            //First the TextViews
            textScore = (TextView) findViewById(R.id.textScore);
            textScore.setText("Score: " + playerScore);
            textDifficutly = (TextView) findViewById(R.id.textDifficulty);

            textDifficutly.setText("Level: " + difficultyLevel);
            textWatchGo = (TextView) findViewById(R.id.textWatchGo);

            //Now the buttons
            button1 = (Button) findViewById(R.id.button);
            button2 = (Button) findViewById(R.id.button2);
            button3 = (Button) findViewById(R.id.button3);
            button4 = (Button) findViewById(R.id.button4);
            buttonReplay = (Button) findViewById(R.id.buttonReplay);
            //Now set all the buttons to listen for clicks
            button1.setOnClickListener(this);
            button2.setOnClickListener(this);
            button3.setOnClickListener(this);
            button4.setOnClickListener(this);
            buttonReplay.setOnClickListener(this);

            //This is the code which will define our thread
            myHandler = new Handler() {

                public void handleMessage(Message msg) {

                    super.handleMessage(msg);

                    if (playSequence) {


                        //All the thread action will go here
//                        button1.setVisibility(View.VISIBLE);
//                        button2.setVisibility(View.VISIBLE);
//                        button3.setVisibility(View.VISIBLE);
//                        button4.setVisibility(View.VISIBLE);

                        switch (sequenceToCopy[elementToPlay]) {

                            case 1:
                                //hide a button
//                                button1.setVisibility(View.INVISIBLE);
                                //play a sound
                                button1.startAnimation(wobble);
                                soundPool.play(sample1, 1, 1, 0, 0, 1);
                                break;

                            case 2:
//                                button2.setVisibility(View.INVISIBLE);
                                //play a sound
                                button2.startAnimation(wobble);
                                soundPool.play(sample2, 1, 1, 0, 0, 1);
                                break;

                            case 3:

//                                button3.setVisibility(View.INVISIBLE);
                                //play a sound
                                button3.startAnimation(wobble);
                                soundPool.play(sample3, 1, 1, 0, 0, 1);
                                break;

                            case 4:
                                //hide a button
//                                button4.setVisibility(View.INVISIBLE);
                                //play a sound
                                button4.startAnimation(wobble);
                                soundPool.play(sample4, 1, 1, 0, 0, 1);
                                break;
                        }

                        elementToPlay++;
                        if (elementToPlay == difficultyLevel) {

                            sequenceFinished();
                            myHandler.sendEmptyMessageDelayed(0, 900);

                        }
                    }
                    myHandler.sendEmptyMessageDelayed(0, 900);


                }


            };//end of thread

            myHandler.sendEmptyMessage(0);

        } catch (IOException e) {
            //catch exceptions here
        }
        playASequence();

    }


    @Override
    public void onClick(View v) {

        if (!playSequence) {//only accept input if sequence not playing

            switch (v.getId()) {
                //case statements...
                case R.id.button:
                    //play a sound
                    soundPool.play(sample1, 1, 1, 0, 0, 1);
                    checkElement(1);
                    break;

                case R.id.button2:
                    //play a sound
                    soundPool.play(sample2, 1, 1, 0, 0, 1);
                    checkElement(2);
                    break;

                case R.id.button3:
                    //play a sound
                    soundPool.play(sample3, 1, 1, 0, 0, 1);
                    checkElement(3);
                    break;

                case R.id.button4:
                    //play a sound
                    soundPool.play(sample4, 1, 1, 0, 0, 1);
                    checkElement(4);
                    break;

                case R.id.buttonReplay:
                    difficultyLevel = 3;
                    playerScore = 0;
                    textScore.setText("Score: " + playerScore);
                    playASequence();
                    break;
            }


        }

    }

    public void createSequence() {

        Log.i("info:", "current high score is: " + hiScore);

        //For choosing a random button
        Random randInt = new Random();
        int ourRandom;


        for (int i = 0; i < difficultyLevel; i++) {
            //Get a random number between 1 and 4
            ourRandom = randInt.nextInt(4);
            ourRandom++;

            //save that number to our array
            sequenceToCopy[i] = ourRandom;


            Log.i("info", "Random Number" + ourRandom);


        }
    }

    public void playASequence() {
        createSequence();
        isResponding = false;
        elementToPlay = 0;
        playerResponses = 0;
        textWatchGo.setText("WATCH!");
        playSequence = true;

    }

    public void sequenceFinished() {

        playSequence = false;
        //make sure all the buttons are made visible
//        button1.setVisibility(View.VISIBLE);
//        button2.setVisibility(View.VISIBLE);
//        button3.setVisibility(View.VISIBLE);
//        button4.setVisibility(View.VISIBLE);
        textWatchGo.setText("Go!");
        isResponding = true;


    }

    public void checkElement(int thisElement) {
        if (isResponding) {

            Log.i("info", "this element being checked is: " + thisElement);

            playerResponses++;
            Log.i("info", "Player repsonses" + playerResponses);
            Log.i("info", "sequence to copy" + Arrays.toString(sequenceToCopy));

            if (sequenceToCopy[playerResponses - 1] == thisElement) {//Correct

                //check whether reaches this part
                Log.i("info", "Correct element!!!");

                playerScore = playerScore + ((thisElement + 1) * 2);
                textScore.setText("Score: " + playerScore);
                ;

// Log.i("info","The difficulty level is: "+difficultyLevel);
                if (playerResponses == difficultyLevel) {//got the whole sequence
                    //don't check anymore
                    Log.i("info", "All elements right!!!");
                    isResponding = false;
                    //Now raise the difficulty
                    difficultyLevel++;
                    //and play another sequence
                    playASequence();


                }
            } else {//wrong answer
                textWatchGo.setText("Failed!");
                //don't checkElement anymore
                isResponding = false;

                Log.i("info", "New high score of: " + playerScore);
                Log.i("info", "The hiScore was: " + hiScore);

                //for our high score
                if (playerScore > hiScore) {

                    hiScore = playerScore;
                    editor.putInt(intName, hiScore);
                    editor.commit();
                    Toast.makeText(getApplicationContext(), "New Hi-Score", Toast.LENGTH_LONG).show();

                }
            }


        }


    }
}

我为自己的利益进行了测试,正如你所说,我在主线程中: -

case 1:
                            //hide a button
                            button1.setVisibility(View.INVISIBLE);
                            //play a sound
                            button1.startAnimation(wobble);
                            soundPool.play(sample1, 1, 1, 0, 0, 1);
                            try {
                                Log.i("info","trying to wait");
                                Thread.sleep(3000);
                            }
                            catch(Exception e){
                                System.out.println("Could not wait");

                            }
                            break;

给出&#34; true&#34;

最新尝试。现在仍然在主线程但Thread.sleep(毫秒)之前播放.Still在按钮动画和声音之间没有正确暂停。什么都没有发生,一次两三个。

if(Looper.myLooper() == Looper.getMainLooper())

我已经尝试了

 case 1:
                            //hide a button
                           button1.setVisibility(View.INVISIBLE);
                            //play a sound
                            try {
                                if(Looper.myLooper() == Looper.getMainLooper())

                                                                    {
                               System.out.println("In main thread!!");
                                    // Current Thread is Main Thread.
                                }
                                Log.i("info","trying to wait");
                                Thread.sleep(3000);
                            }
                            catch(Exception e){
                                System.out.println("Could not wait");

                            }
                            button1.startAnimation(wobble);
                            soundPool.play(sample1, 1, 1, 0, 0, 1);

                            break;

在try catch块中。这也不起作用。两个按钮将立即生成动画。

1 个答案:

答案 0 :(得分:0)

SoundPool play()方法立即返回,声音以异步方式播放。如果它没有,你将无法从主UI线程调用它,因为该线程需要随时准备好处理来自应用程序框架的消息。

出于同样的原因,在主线程上睡觉会产生不良影响(例如Choreographer投诉)。如果你睡得足够长,系统会提出一个没有响应的应用程序&#34;对话框,原因很简单,你的应用程序没有响应(它正在睡觉)。

处理此问题的最简单方法是使用postDelayed()之类的定时消息函数向自己发送延迟消息。这将在指定的延迟后在当前线程上执行Runnable。为每个未来的活动发布一个。

您可以使用单独的线程来驱动计时,但由于您的UI基于View元素,因此您将在线程之间来回传递消息,并且复杂性对于简单的&而言并不是必需的。 #34;短暂延迟后做X&#34;。