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

2017/2/9

Access backgroundMusic from another class

Bennobear Bennobear

2017/2/9

#
Hey i cant find out how to access my backg
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class Start here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Start extends World
{
    GreenfootSound backgroundMusic = new GreenfootSound("dragon-roost.mp3");
    /**
     * Constructor for objects of class Start.
     * 
     */
    public Start()
    {    
        // Create a new world with 600x400 cells with a cell size of 1x1 pixels.
        super(1200, 720, 1); 

    }
    
    public void act(){
        if (Greenfoot.mouseClicked(this))
        {
            Greenfoot.setWorld(new Level_1());
        }
        
    }

    public void stopped()
    {
        backgroundMusic.pause();
    }

    public void started()
    {
        backgroundMusic.playLoop();
    }
}
roundMusic from another class so i can PAUSE it right before my victory sound plays
danpost danpost

2017/2/9

#
You will not be able to unless the Level_1 world has access to it. As is, once you set the new Level_1 world active, there are no references at all to the background music. There are several ways to allow the Level_1 world to get access to it. Passing a reference to the GreenfootSound object to it is one (this can be done via the constructor call or by a separate method). Passing the Start world object is another way (since it contains a reference to the sound). A third way is to make the GreenfootSound object a class object instead of a World instance object (instead of each Start object having its own instance of the background music, all Start objects will share the same instance of the music). Just add the world 'static' to the beginning of line 11 and you can use the following in any other class of the project to get a reference to it:
GreenfootSound bgm = Start.backgroundMusic;
danpost danpost

2017/2/9

#
You may want to assign a new GreenfootSound object in the constructor of the Start world to ensure that the music starts at the beginning when the project is reset. Place at line 20:
backgroundMusic = new GreenfootSound("dragon-roost.mp3");
and change line 11 to:
static GreenfootSound backgroundMusic;
You need to login to post a reply.