Play two sounds with SoundPool - java

I'm a newie to programming and I'm pretty sure that I'm making a dumb mistake here, but I'm stuck and can't manage to fix it.
The error that appears is the following:
Wrong 1st argument type. Found: 'int[]', required: 'int'
This error appears almost at the end of the code, when trying to play the sounds. More specifically at:
spool.play(soundId, 1, 1, 0, 0, 1f);
I'm pretty sure that this could be really easy to fix but I just couldn't do it. Can anyone help me fix it, please?
I decided to just post here the part where I'm having the issue; if someone would like to check the whole thing, it's right in the revisions.
if (rndm == 0) { //I'm just testing it with the horse sound
//right now, so if the random sound that is
//played equals to zero, that's the horse sound
final int[] soundId = new int[2];
soundId[0] = spool.load(actibida.this, R.raw.el, 1); //"el" is the horse sound ID
soundId[1] = spool.load(actibida.this, R.raw.applause, 1); //this is an applause clip I want to be played simultaneously with the horse sound
ImageButton caballo = (ImageButton) findViewById(R.id.caballo); //this is the horse ImageButton ID
caballo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
spool.play(soundId, 1, 1, 0, 0, 1f); //this is
//where I'm
//having the
//issue.
}
});
}

Related

Java Method is skipping return statement

This java method is skipping over a return statement. I was wondering if anybody has encountered this and know of a solution. Whatever the bug is it's very subtle.
public GameState getNextGameState() {
if (player.getLives() > 0) {
if (!player.isAlive()) {
System.out.println("checkpoint 1");
player.setIsAlive(true);
return new PlayField(width, height, hiScores, player.setCoordinates(width / 2, height - 8),
stagePattern, stage);
}
System.out.println("checkpoint 2");
if(++stage > 29)
stage = 0;
return new PlayField(width, height, hiScores, player.setCoordinates(width / 2, height - 8), stage);
}
return new GameOver(Game.key, hiScores, player.getRank());
}
Here is a screenshot with console output to prove it:
Also, this bug only started happening when I put my gamestates in a stack structure. Here is the code I'm now using for the gamestate transition:
public void update() {
gsm.peek().update();
if(gsm.peek().finished)
if(gsm.peek().getNextGameState() == null)
gsm.pop();
else
gsm.push(gsm.pop().getNextGameState());
}
gsm declaration is:
public static Stack<GameState> gsm = new Stack<GameState>();
Hopefully someone has some insight. Thank you!
It is not the result of the same call.
You call twice the method here.
The first time it is not alive, the second is alive. So you have the both message in the output.
In a game, the update phase is called in a continuous way.
Just add a System.out.println at the beginning of the method (that is before the conditions) and you could have the confirmation :
public GameState getNextGameState() {
System.out.println("enter method");
...
}
Can you post more code? You are probably calling it twice and it is not skipping over the return. If you really think it is put a break point to assist you with debugging and watch the code run.

Click on a button to chance textfield 50% chance

im very new to java & android development,
I want a textfield that changes 50% to "You win!" or 50% to "You Lose!" when i click/tap a button.
And a image rotating randomly, like it is 0° then it will get a number between 0 and 100 (higher then 50 is clockwise lower then 50 is counter-clockwise)
i might be asking to much xD but i really dont know how i do this.
How do i do this ?
I actually dont want very advanced answers because im very new to java.
Theres is pretty much nothing in my code except for a button and a textfield.
Here a little help to start off.
First you should add an OnClickListener to your button:
yourButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
handleButtonClick();
}
});
The handleButtonClick()-method could look like this:
private void handleButtonClick() {
// Here we get a random integer between 0 and 99 (including 0 and 99)
int randomNumber = new Random().nextInt(100);
// Here we check if the random number is even
boolean isEven = randomNumber % 2 == 0;
// Now you can do stuff depending on the integer itself (rotation)
// and depending on whether it's even or not.
if(randomNumber < 50){
// do this
} else {
// do that
}
if(isEven){
// do this
} else {
// do that
}
}
To change the text you use:
yourText.setText(...);
But this is really basic stuff you could read on Android TextView
And rotating images was discussed here Android: Rotate image in imageview by an angle
Please read tutorials or refer to this before asking every little thing you could easily look up. Feel free to ask again when you get stuck.
Good luck.
Math.random() method gives you a floating point number between 0-1 but not included 1.
All you have to do is:
int randomNumber = (int)(Math.random()*101);
if(randomNumber < 50)
...
else
...

LibGDX flappy bird clone, Scene2d actor (button)

So, I am developing a flappy bird clone. I created a button which bounces the bird. What I also want for this button is to draw something (totally irrelevant at this point). But not each time the button is hit. I already tried this with:
if (Gdx.input.isTouched()) {
batcher.draw(birdRed, bird.getX(), bird.getY(),
bird.getWidth() / 2.0f, bird.getHeight() / 2.0f,
bird.getWidth(), bird.getHeight(), 1, 1, 1);
}
But this is now what I want. I want specifically to draw something when button is hit first time. I hope you understand my problem. Thanks for your help.
boolean touched = false;
...
if (Gdx.input.isTouched() && !touched) {
touched = true;
batcher.draw(birdRed, bird.getX(), bird.getY(),
bird.getWidth() / 2.0f, bird.getHeight() / 2.0f,
bird.getWidth(), bird.getHeight(), 1, 1, 1);
}
If you use button actor then you can handle change event and use some boolean flag to keep it's first time pressed state.
private boolean wasPressed = false;
Somewhere in button initialization code:
Button pushBirdButton = new Button();
pushBirdButton.addListener(new ChangeListener() {
#Override
public void changed(ChangeEvent event, Actor actor) {
wasPressed = true;
}
});
And then you can always check was you button pressed or not.

Does Score Ninja have to be released to save scores?

So I have Score Ninja up and running on my app. It appears to be coded correctly. When I play through the game and get a score the box pops up and prompts me to input my name and such and then it goes to the other small screen that shows the list. After I input and submit and then exit the 2nd little box and I got to the high scores it does not display any highscores. Then when I play another round I get high score again and the other score is not on the list. Was wondering if anyone has used this and knows much about it. Does it not display and keep track of high scores until the app is released? Or maybe I coded something in wrong and it's not saving it or something. Here is where it is in my code in case you want to see.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(new GameView(this));
// scoreNinjaAdapter = new ScoreNinjaAdapter(
// context, "appid", "key");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
scoreNinjaAdapter.onActivityResult(requestCode, resultCode, data);
}
void onGameOver(){
//
}
Thats the PlayGame class that leads to the surface view. I have tried it with the stuff that is commented above in the code and out. I also had stuff in the onGameOver() but it didnt make any difference either. Here is the code in the surface view that contains it.
#Override
protected void onDraw(Canvas canvas) {
else if (gameState == GAME_OVER){
gameOverTime =(double)(System.currentTimeMillis()-startTime)/100000;
finalScore = score;
canvas.drawRect(0, 0, canvas.getWidth(), canvas.getHeight(), clearPaint);
if(gOverType == 1){
canvas.drawBitmap(bmpBloodOver, null, dst, null);
canvas.drawText("GAME OVER!", canvas.getWidth()/8, canvas.getHeight()/3, whitePaint);
canvas.drawText("KILLS: " + kills, canvas.getWidth()/8, canvas.getHeight()/3+70, whitePaint);
canvas.drawText("SCORE: " + finalScore, canvas.getWidth()/8, canvas.getHeight()/3+140, whitePaint);
}
if (scoreNinja < 1){
ScoreNinjaAdapter scores = new ScoreNinjaAdapter(getContext() , "appid", "key" );
scores.show(finalScore, null, Integer.toString(finalScore));
scoreNinja++;
}
GameLoopThread.running=false;
}
I cut pieces out that had nothing to do with it. The if around the scoreninja score is there to keep the ondraw from redisplaying the boxes over and over. If anyone knows anything about it or any ideas help would be appreciated. Thanks
Here is the Score Ninja site btw http://scoreninja.appspot.com/#HowTo
If scoreninja is an online leader board, make sure you have networking enabled for your app.
If you can't get ScoreNinja working, check out Swarm's Leaderboards, which provide a very similar (simple, free) solution, without requiring the user to download a separate app to have it work :)

Playing sounds simultaneously Android

I am creating a game on Android and I have kind of put this problem off for a while, and am now just coming back to it. In my game I have a background beat, gun sounds, explosions... etc. and I need to be able to play them simultaneously. Right now when I call play on the SoundPool class, the currently playing sound gets interrupted and the new one starts to play. My SoundManager class is below as well as the usage. Any help would be much appreciated as this is really my first game where I have needed this many sound effects. Thanks!
public class SoundManager {
private SoundPool mSoundPool;
private HashMap<Integer, Integer> mSoundPoolMap;
private AudioManager mAudioManager;
private Context mContext;
public SoundManager(Context theContext) {
mContext = theContext;
mSoundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 0);
mSoundPoolMap = new HashMap<Integer, Integer>();
mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
}
public void addSound(int index, int SoundID) {
mSoundPoolMap.put(index, mSoundPool.load(mContext, SoundID, 1));
}
public void playSound(int index) {
float streamVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_RING);
streamVolume = streamVolume / mAudioManager.getStreamMaxVolume(AudioManager.STREAM_RING);
mSoundPool.play((Integer) mSoundPoolMap.get(index), streamVolume, streamVolume, 1, 0, 1f);
}
public void playLoopedSound(int index) {
float streamVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
streamVolume = streamVolume / mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
mSoundPool.play((Integer) mSoundPoolMap.get(index), streamVolume, streamVolume, 1, -1, 1f);
}
}
... and here is an example of how I use the class.
SoundManager sm = new SoundManager(this);
sm.addSound(0, R.raw.explosion);
sm.playSound(0);
... So with this style I add all my sounds to the SoundPool on load and then based on user input I just want to play the sound. Does this look correct? Or should I try and go about this a different way?
Well I did end up figuring this out in case anyone else wants to know. The problem wasn't that it couldn't play more than one sound at a time it was that it was only able to play 4 sounds at a time which gave me the impression that sounds were stopping and starting. In the constructor this line
mSoundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 0);
needed to be changed to allow more streams to play at the same time. So by changing the first argument from a 4 to say, a 20, you could then play 20 sounds at the same time. The game sounds much better now haha. Hope this helps someone.

Categories

Resources