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

2015/2/15

Grabbing a sound variable from a subclass

Kirachan Kirachan

2015/2/15

#
hi, I am trying to do a guitar trainer project, I ran into the issue of trying to do a big method for all my subclasses. so in my subclasses, I have
private static GreenfootSound tone = new GreenfootSound("4e.wav");
   
    public void act() 
    {
        checkKey("y");
    }    
and I want to play tones with my superclass "guitar" which all of my keys extend. my method looks like this:
public void checkKey(String key)
    {
       GreenfootSound temp = this.getTone();
       if(Greenfoot.mousePressed(this))
       {
           temp.play();
        }
       if(Greenfoot.isKeyDown(key))
       {
           temp.play();
        }
    }
    public void checkKey(String fret, String key)
    {
       if(Greenfoot.mousePressed(this))
       {
          this.tone.play();
       }
       if(Greenfoot.isKeyDown(fret) && Greenfoot.isKeyDown(key))
       {
           this.tone.play();
       }
    }
neither one of these way work. The tone that Greenfoot plays is currently the one inside the guitar class, which is not what I desired. So how would I get the subclasses to inherit the method and play the tone that's inside the subclasses instead? Also I have found that Greenfoot can't play the same sound file over and over again, which means that if i keep playing a sound, it doesnt stop itself and start over instead waits for it to finish then start again, and when thats repeated serveral times, all the sounds stop. Is there a way to implement a stop sound thing everytime I press a key then a new sound is played? cheers kira
danpost danpost

2015/2/15

#
As a 'static' field, 'tone' is one field shared by all subclasses of Guitar. If it was not declared static, a field with that name will be given to each instance of it and all subclasses; that is, each instance will have a 'tone' field of its own that can hold a distinct value, one from another. The constructor of the subclasses can assign the value of its field and usually receives that value through a parameter to the constructor ( for example: 'public Tone(String key, String soundFilename)', where a new GreenfootSound object created using 'soundFilename' is assigned to 'tone' ). Replace 'Tone' with the class name of your subclass of Guitar. You should be able to use 'tone.stop();' followed by 'tone.play();' anytime a sound is played to immediately restart the sound (or even to just start the sound, if it is not already playing).
Kirachan Kirachan

2015/2/15

#
thanks man :D
You need to login to post a reply.