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

2016/4/27

The GreenfootSound API method of sound.stop(); is not working for me

LaughingArcher42 LaughingArcher42

2016/4/27

#
I'm coding a game for a group project and I've run into a problem with the sound coding. I've successfully gotten the game to play the sound and play it on loop, but when I'm asking the sound to stop playing, it will not. I am also not sure how to properly use the isPlaying() boolean method within if statements in order to regulate when the sound plays. Here is the code that I have for starting it:
public int soundplay = 1;
    public GreenfootSound music = new GreenfootSound("NinjaTheme.wav");
    public void act() 
    {
        
        if (soundplay == 1 && !music.isPlaying())
        {
            music.playLoop();
            soundplay = 0;
        }
        if (Greenfoot.mousePressed(this))
        {
            Greenfoot.setWorld(new InstructionsWorld());
        }
    }    
And here is the code that I have tried using to stop it:
Start_Button start = new Start_Button();
        if (player != null && isTouching(Player.class))
        {
            removeTouching(Player.class);
            player1.score = 0;
            start.music.stop();
            Greenfoot.setWorld(new GameOverWorld());
        }
I am not sure how to fix the second bit of code to get the sound to stop when the Game Over sequence happens.
danpost danpost

2016/4/27

#
In your second code snippet, you are creating a new Start_Button object, which creates an entirely new instance of the GreenfootSound object which is not yet playing; so, stopping that sound will do nothing. You need to get a reference to the GreenfootSound object already playing to stop it. It is help by your original Start_Button object which is lost when you switch to the InstructionsWorld world (no reference to the old world is retained, which means no reference to the old Start_Button can be acquired. A simple little change in your code will resolve the issue and this is possible because the GreenfootSound object needs to be maintained between world and is not inherently linked to any specific object of the class. Change line 2 to:
public static GreenfootSound music = new GreenfootSound("NinjaTheme.wav");
Then you can refer to it (here, for stopping it) like this (to replace line 6 in the second code snippet):
Start_Button.music.stop();
Remove line 1 from the second code snippet -- this one:
start_Button start = new Start_Button();
LaughingArcher42 LaughingArcher42

2016/4/27

#
Thank you for the help! Making the sound static was all I needed to do :)
You need to login to post a reply.