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

2011/11/5

Multiple piano keys & sounds

jestrada77 jestrada77

2011/11/5

#
New to Greenfoot. How do I modify the code of the Key class so that the keys respond separately. The code should use the new variables keyName and soundFile in its Act and Play classes, rather than hard-coded values like “3a.wav” and “g”. Thanks
danpost danpost

2011/11/10

#
First, in your Key class add the two variables
public Key extends Actor
{
    private String keyName = "";
    private String soundFile = "";
    //  This constructor will recieve the information for the two variables and set those variables accordingly
    public Key(String name, String file)
    {
        keyName = name;
        soundFile = file; 
        //  any other code for constructor here
    }

    public void act()
    {
        if (Greenfoot.isKeyDown(keyName))
        {
            // code to play soundFile here
        }
        else
        {
            // code to ensure soundFile is not playing (if it is, stop it here)
        }
        // any other act code you may have here (I do not think there would be any)
    }
    // other methods you may have here
}
Remember the two variables are unique to each key created and in your world class you can create them with
addObject(new Key("a","LowC.wav"), xLoc, yLoc);
where the first string is the keyboard key pressed to sound the second string sound file.
You need to login to post a reply.