如何通过停止按钮停止播放音乐?

我正在使用 Corona SDK 创建两个按钮,一个用于播放音乐,另一个用于停止。程序在创建停止按钮后正常运行,但是没有声音。请问有人可以帮助我解决问题吗?

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

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

   -- 背景
   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 用于动画]]--
   local soundMusic = audio.loadStream("HappyPants.wav") --[[loadStream 用于背景音乐]]--

 -- 播放音乐的函数
   local function playSound()
     if isAudioOn then
       audio.play(soundMusic)
       print("Boing!")
     end
   end

 -- 控制按钮按下后发生的操作的函数
   local function buttonHit(action)
     if action == "play" then
       playSound()
     elseif action == "stop" then
       audio.stop(playSound)
     end
   end

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

  -- 停止按钮
   local stopButton = widget.newButton{
   label = "停止",
   id = "stop",
   x = 330,
   y= 550,
   labelColor = { default={ 0, 19, 189 }, over={ 0, 19, 189, 1 } },
   onPress = buttonHit
   }
点赞
用户88888888
用户88888888

你的 buttonHit 函数是错误的。

尽管你传入了参数 action,但由于你使用的是 widget 库,所以传入函数中的唯一参数是 event。另外,你给按钮设置了 id 而不是 action。这个 id 属于事件目标,也就是被按下的按钮。

你需要的代码类似如下:

local function buttonHit( event )
  if event.target.id == "play" then
    playSound()
  else
    audio.stop(playSound)
  end
end
2020-01-27 08:13:50