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

2021/4/5

Can't stop music from the World itself or an actor

hernry2812 hernry2812

2021/4/5

#
I basically would like to play the music only in my menu, so I want the start button of the game to stop the music. However, it keeps crashing. Without stopping the music it works totally fine. In my menu I have some buttons which set you back to StartScreen world, so I have to check if music is already played so it doesn't play twice. But that works totally fine, just in case you were wondering. This is my start screen which starts playing my music:
public class StartScreen extends World
{
    public static GreenfootSound menuMusic;
    public static boolean musicPlayed = false;

    public StartScreen()
    {    
        super(800, 800, 1);
        prepare();
    }
    
    public void prepare()
    {
        addObject(new StartButton(), 90, 340);
        addObject(new SettingsButton(), 90, 410);
        addObject(new InfoButton(), 90, 480);
        
    }
    
    public void act()
    {
        playMusic();
        setBackgroundImage();
    } 
    
    public static void stopMusic()
    {
        menuMusic.stop();
    }
    
    public static void playMusic()
    {
        if(!musicPlayed) 
        {
            GreenfootSound menuMusic = new GreenfootSound ("menumusicfinal.mp3");
            menuMusic.playLoop();
            musicPlayed = true;
        }
    }
}
In my Actor class of the StartButton I have the following method:
public void selectMushroomForest()
    {
        if (Greenfoot.mouseClicked(this))  
        {  
            StartScreen.stopMusic();
            Greenfoot.setWorld(new MushroomForest());
        }
    }
I also tried to stop the music within the world, but no matter if I do this or just try to stop it from an actor it keeps crashing with the following error code:
java.lang.NullPointerException
	at StartScreen.stopMusic(StartScreen.java:51)
	at StartButton.selectWillmsValley(StartButton.java:62)
	at StartButton.setWorldIfClicked(StartButton.java:27)
	at StartButton.act(StartButton.java:15)
	at greenfoot.core.Simulation.actActor(Simulation.java:567)
	at greenfoot.core.Simulation.runOneLoop(Simulation.java:530)
	at greenfoot.core.Simulation.runContent(Simulation.java:193)
	at greenfoot.core.Simulation.run(Simulation.java:183)
Gbasire Gbasire

2021/4/5

#
Try to declare the "GreenfootSound menuMusic = new GreenfootSound ("menumusicfinal.mp3");" directly in the variable field instead of in the playMusic() method.
danpost danpost

2021/4/5

#
Remove the declaring type "GreenfootSound" from the beginning of line 35 so you do not create a local variable.
You need to login to post a reply.