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

2014/1/25

Setting Sound Volume

bernhard bernhard

2014/1/25

#
I'm stuck with the following problem: I have a MainmenuWorld, where I start playing a sound named "song" in a loop.
1
2
GreenfootSound song = new GreenfootSound ( "song.mp3" );
song.playLoop();
I made two constructors for the MainmenuWorld, only one plays the song (the one with no variables passed) because when I set another world and then come back to the Mainmenu, the song is played again and so its played double times at once. My problem is: I want to be able to turn the song on and off again and I want to do it with setting its volume to 0 / 100. I just tried it with:
1
2
if ( Greenfoot.isKeyDown ("g") ) song.setVolume ( 0 );
if ( Greenfoot.isKeyDown ("f") ) song.setVolume ( 100 );
It works but when I go to another world and come back to the Mainmenu again it doesn't. How can I solve that?
davmac davmac

2014/1/25

#
when I go to another world and come back to the Mainmenu again it doesn't
Are you coming back to the same world instance, or a new world instance? (i.e. are you calling 'new MainMenu()'?)
bernhard bernhard

2014/1/25

#
It's a "new MainMenu()"
bernhard bernhard

2014/1/25

#
I guess I see your point. I should make the MainMenu pass itself to World2 and when World2 sets the MainMenu again, it's not "setWorld ( new Mainmenu() );" but "setWorld ( mainmenuworld );", mainmenuworld being the passed variable. Shouldn't I?
danpost danpost

2014/1/25

#
bernhard wrote...
I should make the MainMenu pass itself to World2 and when World2 sets the MainMenu again, it's not "setWorld ( new Mainmenu() );" but "setWorld ( mainmenuworld );", mainmenuworld being the passed variable. Shouldn't I?
As an alternative, you could just pause or stop the music before going to the World2 world:
1
2
song.stop();
Greenfoot.setWorld(new World2());
Or, set the GreenfootSound field as 'public static' (make it a class field instead of an instance field). Then it can be controlled from almost anywhere in the project:
1
MainMenu.song.setVolume(0); // or any other GreenfootSound method
davmac davmac

2014/1/25

#
I should make the MainMenu pass itself to World2 and when World2 sets the MainMenu again, it's not "setWorld ( new Mainmenu() );" but "setWorld ( mainmenuworld );", mainmenuworld being the passed variable. Shouldn't I?
Yes :)
bernhard bernhard

2014/1/25

#
Stopping the music is not what I want, I want the music to be played all the time if its not turned off. I set the sound to a static field and it works now. Perfect! Thank you.
You need to login to post a reply.