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

2018/4/21

Music

Heet_Patel Heet_Patel

2018/4/21

#
Is it possible to have a button for music on and off and it will actually turn music on and off just by a click of the button
DavranbekRozmetov DavranbekRozmetov

2018/4/21

#
It is is very easy to make. first you need to have a Boolean to control the music and keep track of the clicks. for example I did something like
boolean playMusic = true;
then you will need to import the sound
 GreenfootSound sound = new GreenfootSound("Name.FileFormat");
then you will need to get the sound icon and make an image.
GreenfootImage music= new GreenfootImage("images/speaker.png");

on act method you can write something like
 if (Greenfoot.mouseClicked(this) && !playMusic) {
           playMusic = true;
        } else if(Greenfoot.mouseClicked(this) && playMusic){
           playMusic = false; 
        }
        

    if(playMusic){
        sound.playLoop();
    } else{
        sound.stop();
    }
setImage(img);
You can change the image when the playMusic is true or false as well
Heet_Patel Heet_Patel

2018/4/21

#
whats a boolean and how do i get it
DavranbekRozmetov DavranbekRozmetov

2018/4/21

#
I mean declare boolean. you just need to write the following down
boolean playMusic = true;
Heet_Patel Heet_Patel

2018/4/21

#
where do i write it down
DavranbekRozmetov DavranbekRozmetov

2018/4/21

#
boolean playMusic = true;
GreenfootSound sound = new GreenfootSound("Name.FileFormat");
// write the location, name and file format of your music file
GreenfootImage music= new GreenfootImage("images/speaker.png");
// write the location, name and file format of your image file

public void act(){
if (Greenfoot.mouseClicked(this) && !playMusic) {
           playMusic = true;
        } else if(Greenfoot.mouseClicked(this) && playMusic){
           playMusic = false; 
        }
         
 
    if(playMusic){
        sound.playLoop();
    } else{
        sound.stop();
    }
setImage(img);
}
copy the whole code and replace it with your old code. and also can I see your code
Heet_Patel Heet_Patel

2018/4/21

#
yeah
Heet_Patel Heet_Patel

2018/4/21

#
it says cannot find variable img for the 20th line
Heet_Patel Heet_Patel

2018/4/21

#
i can update the game without compling but there is an error
DavranbekRozmetov DavranbekRozmetov

2018/4/21

#
can you send me the whole code please
danpost danpost

2018/4/21

#
Maybe you can take example from my BgMusic Actor Class Demo scenario, which you can run to view the code. It is also down-loadable.
You need to login to post a reply.