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

2019/4/7

Sound problem

renniemm renniemm

2019/4/7

#
I have a subclass of world that is my start page and it switches to the game world (called "MyWorld") when the user hits the space button. Background music also starts when it runs and continues as the game plays. The problem is that when I added the menu subclass, now the music won't stop when the game ends even though I used backgroundMusic.stop(). I assume it has something to do with me starting it in the other subclass but I'm not sure how to fix this. This is my menu subclass (doesn't look like much because it only displays an image):
public class Menu extends World
{

   
    public Menu()
    {    
        
        super(600, 300, 1); 
        
        Greenfoot.start();
        
    }
     GreenfootSound backgroundMusic = new GreenfootSound("nyanmusic.mp3");
     public void started(){
       
        backgroundMusic.playLoop();
    }
    public void stopped(){
        backgroundMusic.stop();
    }

    public void act(){
        if (Greenfoot.isKeyDown("space")) {
            Greenfoot.setWorld(new MyWorld());
    }
}
}
And here are the act, started, and stopped methods in the MyWorld subclass. As you can see I have it stop in stopped() as well as in the if statements where the game ends but neither work.
public void act(){
        
        showTime();
        if(timer>0){
            timer --;
            if(timer == 0){
                Greenfoot.stop();
                failed();
                backgroundMusic.stop();
                Greenfoot.playSound("fail.mp3");

            }
        }
        List cupcakes = getObjects(Cupcake.class);
        if(cupcakes.size()==0){
            Greenfoot.stop();
            showEndTime();
            backgroundMusic.stop();
            Greenfoot.playSound("victory.mp3");
            

        }
        List broccoli= getObjects(Broccoli.class);
        if(broccoli.size()<15){
            Greenfoot.stop();
            backgroundMusic.stop();
            Greenfoot.playSound("fail.mp3");
            ateBroccoli();
        }
    }

    public void started(){
        backgroundMusic.playLoop();
    }

    public void stopped(){
        backgroundMusic.pause();
    }
Any help would be appreciated! Thanks!
Super_Hippo Super_Hippo

2019/4/8

#
Both backgroundMusic objects have the same name, but are different objects. You could stop the music when you change the world and start a new one in the next world. Or you have the music in one class and stop that specific music then.
//in Menu – line 13
public static GreenfootSound backgroundMusic = new GreenfootSound("nyanmusic.mp3");
//in MyWorld change all
backgroundMusic
//to
Menu.backgroundMusic
renniemm renniemm

2019/4/8

#
It works now- thank you!
You need to login to post a reply.