gpt4 book ai didi

java - 如何停止在简单的 Android 游戏中同时播放所有声音和动画?

转载 作者:太空狗 更新时间:2023-10-29 14:54:54 25 4
gpt4 key购买 nike

我正在阅读 John Horton 的《Learning Java by Building Android Games》一书。

Link to book Java by Building Android Games by John Horton

这是一本非常好的书,我正在通过它输入游戏。我有一个内存游戏正在运行,它会按长度逐渐增加的顺序播放四个按钮之一的声音(每转一圈)。

我的代码存在的问题是按钮振动并发出声音的时间对我作为用户来说似乎是同一时间。

我怎样才能添加延迟来立即阻止所有事情发生?第一个序列只有一个按钮,所以它只会振动和发出一个按钮的声音 - 所以不会混淆。

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

我试过了:

     ...
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;
...

对于每个按钮/case 语句 - 但它不起作用。

Memory Game - Game Screen with buttons

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;

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

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

给出“真”

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

 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;

我试过了

button1.wait(3000) ;

在 try catch block 中。这也不起作用。两个按钮将同时动画。

最佳答案

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

出于同样的原因,在主线程上 hibernate 会产生不良影响(例如 Choreographer 投诉)。如果您 hibernate 的时间足够长,系统将显示“应用程序未响应”对话框,原因很简单,即您的应用程序未响应(它正在 hibernate )。

处理此问题的最简单方法是向自己发送延迟消息,使用一种定时消息功能,如 postDelayed() .这将在指定的延迟后在当前线程上执行 Runnable。为每个 future 的事件发布一个。

您可以使用单独的线程来驱动计时,但由于您的 UI 基于 View 元素,您将在线程之间来回传递消息,对于简单的“执行 X 操作”而言,复杂性不是必需的短暂的延迟”。

关于java - 如何停止在简单的 Android 游戏中同时播放所有声音和动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32462838/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com