SKAudioNode problem

I have a problem with the SKAudioNode. The game ends with the Home Button. An audio file will be played.

When I return, the audio file will continue to play.

I want to stop it.

I have tried many things but without success.


self.AudioNodeSet.removeFromParent() // does not work

self.AudioNodeSet.run(SKAction.stop()) // the same


Can anyone help me?


class GameScene: SKScene {
 var AudioNodeSet = SKAudioNode()
     override func didMove(to view: SKView) {
     self.addChild(AudioNodeSet) // Audio Node
        AudioNodeSet.name = "AudioNodeSet"
......
func applicationWillResignActive(_ application: UIApplication) {
        let imageView = UIImageView(frame: self.window!.bounds)
        imageView.tag = 101
        imageView.backgroundColor = UIColor.white
        //imageView.contentMode = .center
        imageView.contentMode = .scaleAspectFill
        let pic = UIImage(named: "Start Page.jpg") // Overwrite Return Scene
        imageView.image = pic
        UIApplication.shared.keyWindow?.subviews.last?.addSubview(imageView)
    }

........

override func didMove(to view: SKView) {
        
        print("$$$ GameScrene load")
        scene?.size = CGSize(width: 1920, height: 1080)
        scene?.backgroundColor = .black 
        scene?.scaleMode = .aspectFill 
        
        let notificationCenter = NotificationCenter.default
        notificationCenter.addObserver(self, selector: #selector(appMovedToBackground), name: UIApplication.willResignActiveNotification, object: nil)
        notificationCenter.addObserver(self, selector: #selector(appMovedToForeground), name: UIApplication.didBecomeActiveNotification, object: nil)
        notificationCenter.addObserver(self, selector: #selector(appWillTerminate), name: UIApplication.willTerminateNotification, object: nil)

.........

@objc func appMovedToForeground() {
        
        print("applicationWillResignActive -> appMovedToForeground")
        self.AudioNodeSet.run(SKAction.stop()) // not work!
        self.AudioNodeSet.removeFromParent() // second try -> not work!

This code is executed when the game continues.

The rest of the audio file can then be heard.

Replies

So I don't understand your question!

the didMove function, is called always when the scene will appear!

So once you go to background and back the didMove will called again, and the AudioSet will added one more time on scene! That is the problem the removeFromParent is not working. In fact is working but the didMove func added the node again!

Hope this help 😎