This site requires JavaScript, please enable it in your browser!
Greenfoot back
n1ght5t41xX
n1ght5t41xX wrote ...

2019/3/11

Problems with playing a different sound for different keys

n1ght5t41xX n1ght5t41xX

2019/3/11

#
Hello, Greenfoot community :) I have to hand something in tomorrow, and you are my last resort. I think, for you, the problem is quite simple to solve, but because I'm a rookie, this isn't the case concerning myself. So, I need to create a piano. Till tomorrow, we need to have two working keys playing different sounds and were supposed to do that with strings. I just can't get the hang of it...my two keys play the same sound, but I barely know anything, so I didn't experiment much. Here is my code: How will I get this to work? Thanks in advance! Night
public Key(String key, String sound)
    {
        isDown = false;
        
        
    }

public void act()
    {
        play(); 
    }

    public void play()
    {
        if (Greenfoot.isKeyDown("t") && !isDown)      
        {
            Greenfoot.playSound("2a.wav");
            setImage("white-key-down.png");
            isDown = true;
        }

        else if (isDown == true && !Greenfoot.isKeyDown("t")) 

        {
            isDown = false;
            setImage("white-key.png");
        }

       
    }
}

Super_Hippo Super_Hippo

2019/3/11

#
The code which is executed when a Key is created (new Key(….)) is the constructor (lines 1-6). There are two String parameters. You need to save those passed parameters for the key so the key knows which sound to play and when. The trigger "when" the sound should be played is in line 15. When "t" is pressed. This should be the key you passed to the constructor instead. In line 17, the sound "2a.wav" is played. Instead, you want to play the sound file which was passed to the constructor.
danpost danpost

2019/3/11

#
Show the code you are using to create the keys.
n1ght5t41xX n1ght5t41xX

2019/3/11

#
@danpost
private void prepare()
    {

        Key key = new Key("t", "2a");
        addObject(key,71,138);
        Key key2 = new Key("z", "2b");
        addObject(key2,151,145);
        key2.setLocation(146,137);
    }
danpost danpost

2019/3/11

#
Okay -- so you are passing two keys ("t" and "z") and two sound file names ("2a" and "2b", without suffixes) to the Key constructor. These value can be saved in fields in the Key class. Then, instead of using the literals on lines 15 and 17, you can use the appropriate field names.
n1ght5t41xX n1ght5t41xX

2019/3/11

#
//PROBLEM SOLVED I managed to abstract the keys. Thank you all.
You need to login to post a reply.