(Redirected from Sound on/off Button)

Please expand this article or section. You can help by adding more information if you are an editor. More information might be found in a section of the talk page. (August 2018)
Note Warning: Loud sounds (such as screams and certain genres of music) can hurt the viewer's ears or even cause deafness, especially if the volume is set too high or the user is using head/earphones. When using such sounds, it is always wise to add a warning in the Notes and Credits or lower the volume of the audio if possible. Even so if it is too loud your project may be taken down by the Scratch Team.

A sound toggle button may be useful for games with music that plays continuously, as well as pause menus.

Muting Audio

The below script does not pause the audio, but instead mutes it. Setting volume to 0% will result in silent audio that cannot be heard, yet plays silently.

when gf clicked
switch costume to (sound-on v)

when this sprite clicked
next costume
if <(costume [number v]) = [2]> then //assuming the second costume is "off" and the first "on"
set volume to (0)% //if now off, turn off the volume
else
set volume to (100)% //if now on, turn on the volume
end

This script can be modified to allow the volume to be changed.


Below is a more complex method that uses maths to find out if the volume should be set to 100% or 0%:

when this sprite clicked
set volume to (((((volume) / (100)) + (1)) mod (2))*(100))%

Note that the 'on' volume can be changed by altering the value of inputs with the current values of 100.

Pausing Audio

Although there is no in-built method for pausing soundtracks, there is a simple way of doing this using the set [pitch v] effect to [] block. The pitch effect alters how high or low the sound is, meaning that the higher the value, the faster the sound is played. Setting the effect to an infinitely low value would result in an audio track lasting forever. One divided by zero is equal to Infinity, hence -1 divided by 0 is equal to negative Infinity

when this sprite clicked
if <(costume [name v]) = [off]> then
    set [pitch v] effect to ([-1]/[0]) // Equal to negative Infinity
    set volume to [0]%
end
if <(costume [name v]) = [on]> then
    set [pitch v] effect to ([1]/[0]) // Equal to Infinity
    set volume to (100)% // The inputed value can be changed if required.

See Also

Cookies help us deliver our services. By using our services, you agree to our use of cookies.