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

2013/4/29

Calling variable from constructor in method to play/stop sound

mattdodo mattdodo

2013/4/29

#
So I am having trouble getting
song.stop();
which is in the method stopped() to be called from
GreenfootSound song = new GreenfootSound(sound);

in the constructor of the class Full Code:
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class Number here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Number extends Actor
{
    int arrayposition;
    String value;
    public String sound;
  
    public Number(int position, String value, String soundFile)
    {
        arrayposition = position;
        this.value = value;
        sound = soundFile;
        //GreenfootSound song = new GreenfootSound("soundFile");
    }
    /**
     * Act - do whatever the Number wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        
    }
    public void startSong()
    {
        int i =0;
        while (i <1)
        {
            
            
                play();    
                i=i+1;
                //Greenfoot.delay(30);
                //Greenfoot.stop();
                System.out.println("a");
            
        }
    }
    public void stopSong()
    {
        int i =0;
        while (i <1)
        {
            
                //song.stop();
                stopped();    
                i=i+1;
                //Greenfoot.delay(30);
                //Greenfoot.stop();
                System.out.println("b");
            
        }
    }
     public void play()
    {
        //GreenfootSound song = new GreenfootSound(sound);
        Greenfoot.playSound(sound);
    }
    public void stopped()
    {
        //GreenfootSound song = new GreenfootSound(sound);
        song.stop();
    }
    
}
danpost danpost

2013/4/29

#
You cannot use 'song.stop()' unless you first use 'song.play()' and have a reference to 'song' declared in the class. Therefore, in your 'play' method, use 'song.play()'. In your field declaration area, change line 13 to 'private GreenfootSound song;'; then in your constructor, change line 19 to 'song = new GreenfootSound(soundFile);'. You can remove lines 32, 33, 34, 38, and 43; as the 'loop' will only run once anyway. You can remove lines 47, 48, 49, 53, and 58; as the 'loop' will only run once anyway.
You need to login to post a reply.