Search code examples
luacoronasdk

How do I stop Music from playing with my stop button?


I am creating two buttons, using Corona SDK, one for playing music and the other for stopping. The program works fine up until i create the stop button and nothing works. There is no audio. Can someone help me resolve this please?

          local widget = require("widget")
          display.setStatusBar(display.HiddenStatusBar)

            centerX = display.contentWidth * .5
            centerY = display.contentHeight * .5

   -- Background
   local bg = display.newImageRect("bg_iPhone.png", 1100, 3200)
   bg.x = centerX
   bg.y = centerY

   local isAudioOn = true

   local soundJump = audio.loadSound("boing.mp3") --[[loadSound is for animations]]--
   local soundMusic = audio.loadStream("HappyPants.wav") --[[loadStream is for background music]]--

 --Sound function to play music
   local function playSound()
     if isAudioOn then
       audio.play(soundMusic)
       print("Boing!")
     end
   end

 -- Button Function that controls what happens after button is pressed
   local function buttonHit(action)
     if action == "play" then
       playSound()
     elseif action == "stop" then
       audio.stop(playSound)
     end
   end

 -- Play Button
   local playButton = widget.newButton{
   label = "Play",
   id = "play",
   x = 330,
   y = 500,
   labelColor = { default={ 0, 19, 189 }, over={ 0, 19, 189, 1 } },
   onPress = buttonHit
   }

  -- Stop Button
   local stopButton = widget.newButton{
   label = "Stop",
   id = "stop",
   x = 330,
   y= 550,
   labelColor = { default={ 0, 19, 189 }, over={ 0, 19, 189, 1 } },
   onPress = buttonHit
   }

Solution

  • Your buttonHit function is wrong.

    You pass in the argument action, however, since you are using widget library, the only thing that gets passed into the function is event. Also, you've given the buttons an id, not an action. This id then belongs to the event target, i.e. the button that is being pressed.

    What you want is something along the lines of:

    local function buttonHit( event )
      if event.target.id == "play" then
        playSound()
      else
        audio.stop(playSound)
      end
    end