Add sound switch off/on button corona sdk

884 views Asked by At

I need help with adding sound off/on button to my game. In global variable lua file, I have the following:

local sounds = {}
sounds["select"] = audio.loadSound("sounds/select.mp3")
sounds["score"] = audio.loadSound("sounds/score.mp3")
G.playSound = function(name) 
    if sounds[name] ~= nil then 
        audio.play(sounds[name])
    end
end

In games.lua file, I call the function as:

utils.playSound("score")

I have a soundon.png and soundoff.png files both in a sprite sheet (not sure if that is a good idea), all I am trying to implement is when you click the sound button, all sounds stops and it displays the soundoff image, vice versa. Thanks

1

There are 1 answers

0
joehinkle11 On

I personally wouldn't use a sprite sheet. Just load both images and toggle their "isVisible" field. Then toggle a variable which would stop your sounds. Try something like this.

myGlobalSoundToggle = true
local image = display.newImage("soundon.png")
local image2 = display.newImage("soundoff.png")
image2.isVisible = false

local function onTap( self, event )
    image.isVisible = ~image.isVisible
    image2.isVisible = ~image2.isVisible
    myGlobalSoundToggle = image.isVisible
    return true
end 
image:addEventListener( "tap", onTap )

Now that we have our buttons working, we need to toggle the sound on and off.

local sounds = {}
sounds["select"] = audio.loadSound("sounds/select.mp3")
sounds["score"] = audio.loadSound("sounds/score.mp3")
G.playSound = function(name) 
    if (sounds[name] ~= nil) and (myGlobalSoundToggle) then 
        audio.play(sounds[name])
    end
end