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

2021/11/16

start and stop music by if-statement but how?

CodingCowgirl CodingCowgirl

2021/11/16

#
Hey, guys! So, I’m still working on this quiz. Now my problem is that the music starts as soon as I open my Greenfoot project. I have an idea for a code to solve this problem. However, it doesn’t work at all. So, my plan is a Boolean which asks if the specific world is true. How do I solve my problem?
private GreenfootSound background = new GreenfootSound("background.mp3");
    
    /**
     * Constructor for objects of class MainMenu.
     * 
     */
    public MainMenu()
    {    
        // Create a new world with 600x400 cells with a cell size of 1x1 pixels.
        super(1920, 1080, 1); 
         GreenfootImage bg = new GreenfootImage("london-background.png");
         bg.scale(getWidth(), getHeight());
         setBackground(bg);
         mainMenu();
    }
    
    private void mainMenu() {
        Logo logo = new Logo();
        addObject(logo, 960, 540);
        Greenfoot.playSound("background.mp3");
    }
    
    private void startMusic() {
        background.playLoop();
    }
    
    private void stopMusic() {
        background.stop();
    }
    
    private void backgroundMusic() {
        if (World.MainMenu = true) {
            startMusic();
        } else {
            stopMusic();
        }
    }
 
    public void act() {
         if(Greenfoot.isKeyDown("enter")) {
             Greenfoot.playSound("mouse-click.mp3");
             Greenfoot.setWorld(new playQuiz());
            }
    }
danpost danpost

2021/11/16

#
Currently, you have no way to control the music at all because you are using Greenfoot.playSound which does not give you a reference to any GreenfootSound object. Instead, create a GreenfootSound object and retain it in a class field so you can access it from anywhere in your project. You can then stop the sound when changing world (either before, during or after creating the new world).
You need to login to post a reply.