Swift-how do I perform a function after the audio is finished with SKAudioNode and

backgroundMusic =SKAudioNode(fileNamed: "audio.mp3")
backgroundMusic.autoplayLooped = false
addChild(backgroundMusic)    
backgroundMusic.runAction(SKAction.play())

After all the audio sounds, I need to run a function, but I don't know how to do it.

Any suggestions?

Update

Option 1

I have a button that I pinch and causes a SKSpriteNode called miaumHelp to shrink, then if I press it again it enlarges, after it is enlarged an audio sounds, and it shrinks, but it shrinks before the audio ends, it doesn't wait for the audio, the idea is that the audio ends and after that it shrinks.

So what I need is that after the audio sounds complete, it shrinks not before.

Here is my code.

if toggleMiaumHelpState {
    toggleMiaumHelpState = false
    miaumHelp.runAction(SKAction.scaleTo(0.2, duration: 0.5), completion: { print("small")})
    backgroundMusic.runAction(SKAction.stop())
} else{
    toggleMiaumHelpState = true
    miaumHelp.runAction(
        SKAction.scaleTo(1.0, duration: 0.5), completion: {
            print("big")
            self.backgroundMusic.runAction(
                SKAction.play(),
                completion:{
                    //Se ejecuta de inmediato, no espera que termine el audio.
                    self.miaumHelp.runAction(SKAction.scaleTo(0.3, duration: 0.5), completion: {
                            print("small again 0.3")
                     })
              }  
          )
    })
}

Option 2

I have a button that by doing pinch causes its size to decrease a SKSpriteNode called miaumHelp, then if I press it again it enlarges, after it is enlarged it sounds an audio, and then it shrinks, here it shrinks after the audio is finished, but if I press the button again, I have no stop the audio and do not run the actionSmallAgain Action.

Here the audio works, but you can not cancel the sound or the effect that follows.

if toggleMiaumHelpState {
    toggleMiaumHelpState = false
    miaumHelp.runAction(SKAction.scaleTo(0.2, duration: 0.5), completion: {
        print("small")
    })
} else{ 
    toggleMiaumHelpState = true
    miaumHelp.runAction(SKAction.scaleTo(1, duration: 0.5), completion: {
    print("big")    
    self.runAction(
             SKAction.playSoundFileNamed("audio.mp3", waitForCompletion: true)
              ,completion: {
                     self.miaumHelp.runAction(SKAction.scaleTo(0.4, duration: 0.5), withKey: "actionSmallAgain")
                     print("small again")
               }
         )
    })
}
 1
Author: Angel Angel, 2016-01-14

1 answers

I finally did it with AVAudioPlayer which has a function that runs when an audio terminates, called:

audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool)
 0
Author: albertcito, 2016-01-18 15:22:09