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

2018/6/23

Is it possible to control a whole game sound volume by a code?

akael888 akael888

2018/6/23

#
So guys, im going to insert a bunch of sound effect on my game, also i added some kind of button that could control the sounds volume. Is it possible that i could just create some lines of code that could just control the master volume of the game?
danpost danpost

2018/6/23

#
Yes. However, here are some things to keep in mind. (1) You cannot use Greenfoot.playSound method; You can only control the volume of a GreenfootSound object. (2) You must have a reference to all GreenfootSound objects created, so you can adjust their volume; This reference only needs to persist only long enough for the volume to be set and sound to be started. (3) The volume field should be a public static int field; This will make it easy to access when needed.
danpost danpost

2018/6/23

#
An interesting way to handle sound is with a class like the following:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import greenfoot.*;
 
public abstract class Sound extends Greenfoot
{
    private static GreenfootSound bgMusic;
    private static int volume = 50;
     
    public static int getVolume()
    {
        return volume;
    }
     
    public static void setVolume(int vol)
    {
        volume = vol;
        if (volume > 100) volume = 100;
        if (volume < 0) volume = 0;
        if (bgMusic != null && bgMusic.isPlaying()) bgMusic.setVolume(volume);
    }
     
    public static void playSound(String filename)
    {
        GreenfootSound sound = new GreenfootSound(filename);
        sound.setVolume(volume);
        sound.play();
    }
     
    public static void setSoundVolume(GreenfootSound sound)
    {
        sound.setVolume(volume);
    }
     
    public static void setBackgroundMusic(String filename)
    {
        setBackgroundMusic(new GreenfootSound(filename));
    }
     
    public static void setBackgroundMusic(GreenfootSound bgm)
    {
        if (bgm == bgMusic) return;
        if (bgMusic != null) bgMusic.stop();
        bgMusic = bgm;
        if (bgMusic != null) bgMusic.setVolume(volume);
    }
     
    public static void playBackgroundMusic(boolean play)
    {
        if (bgMusic != null)
        {
            if (play) bgMusic.playLoop(); else bgMusic.pause();
        }
    }
    }
}
You can call Sound.playSound instead of Greenfoot.playSound and there are methods to control both background music as well as incidental sounds. The only thing you would need is a value display actor.
You need to login to post a reply.