How to stop a audio after it has finished.

Cause I’m looking for a solution for my space shooter game where I want to stop firing the lasers and the audio after the touch event has ended.

OK.  Now I get it. 

All of this is clearly outlined in the docs.  I think you overlooked the fact that audio.stop() stops a sound channel, not a loaded sound handle. 

However, it is also possible that you’re new to the idea of sound playing in general.   So, let me walk you through it…

  1. Get a free channel:  (this returns a number)(https://docs.coronalabs.com/api/library/audio/findFreeChannel.html)

  2. Play the sound you want to stop later, on that channel.

  3. When you stop, pass in the number of the channel.

This should work:

local channel local function onTouch(event) local phase = event.phase if phase == "began" then channel = audio.findFreeChannel() audio.play(soundFile, { loops=-1, channel = channel }) elseif phase == "ended" then audio.stop(channel) end end object:addEventListener("touch", onTouch)

Once you’ve tried that, and assuming it works, let me suggest a much better solution:

function object.touch( self, event ) local phase = event.phase local id = event.id if phase == "began" then display.getCurrentStage():setFocus( self, id ) self.isFocus = true self.channel = audio.findFreeChannel() audio.play(soundFile, { loops=-1, channel = self.channel }) elseif self.isFocus then if phase == "ended" then display.getCurrentStage():setFocus( self, nil ) self.isFocus = false audio.stop(self.channel) end end return false end object:addEventListener("touch")

This is a more advanced listener.  It has these benefits:

  • attached to button, so ‘self’ is the button.
  • you can use self to store values (a sort of scratch pad) like I did with ‘channel’
  • When the button is destroyed, the listener is automatically removed.
  • If you touch the button, slide your finger off the button, then lift your finger, the ‘stop sound’ code will still execute.
    • Try this with the old listener and notice the ‘ended’ phase never executes so the sound continues forever.
  • It is compatible with multi-touch and single-touch configurations.

Is there a reason the original post is just a series of astericks?

Any one else wanting to learn from this thread won’t know what it’s about now.

Rob

I told the OP the question was unclear and I think he got frustrated and wiped it.   Eventually, we got this resolved (I believe), but I really wish he’d go back and re-edit the original question and make it clear so future readers can benefit.