How to dismiss music when game scene exits

I am having difficulty figuring out how to dismiss background music after the game scene exits. Currently, the music still plays until it is finished or the app closes. I want the music to stop if the particular game scene is closed.

Music added as SKAction in my game scene:

let backgroundMusic =   SKAction.playSoundFileNamed("Pickle Race theme.m4a", waitForCompletion: true)
        run(backgroundMusic, withKey: "bm")
    }

Function for returning to main menu and dismissing music:

func returnToMainMenu(){

        viewController?.dismiss(animated: true, completion: nil)

        removeAction(forKey: "bm"
    }

returnToMainMenu() called in touchesBegan()

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        if let touch = touches.first {

                   let location = touch.location(in: self)

                   let touchedNodes = self.nodes(at: location)

            if touchedNodes.contains(where: { $0.name == "math"} ) {

                mathArray.shuffle()

                mathLabel.text = mathArray.randomElement()

                return

            }

            for node in touchedNodes.reversed() {

                if node.name == "back" {

                    returnToMainMenu()

                }

            }
                   for node in touchedNodes.reversed() {

                       if node.name == "draggable" {

                           self.movableNode = node

                       }

                   }

           }

    }

What am I doing wrong, and how can I dismiss the music when the scene is dismissed?

Answered by ThirdGradeTeacher in 678848022

I solved my own problem...I added backgroundMusic as an SKAction when it should have been an SKAudioNode. To make the music stop when I exit the game scene, I removed:

let backgroundMusic =   SKAction.playSoundFileNamed("Pickle Race theme.m4a", waitForCompletion: true)
        run(backgroundMusic, withKey: "bm")
    }

and the corresponding removeAction;

and added:

let backgroundMusic = SKAudioNode(fileNamed: "Pickle Race theme.m4a")

        addChild(backgroundMusic)

Also, I noticed after I posted there is a missing closure; correcting it obviously didn't help since the code was wrong anyway.

Accepted Answer

I solved my own problem...I added backgroundMusic as an SKAction when it should have been an SKAudioNode. To make the music stop when I exit the game scene, I removed:

let backgroundMusic =   SKAction.playSoundFileNamed("Pickle Race theme.m4a", waitForCompletion: true)
        run(backgroundMusic, withKey: "bm")
    }

and the corresponding removeAction;

and added:

let backgroundMusic = SKAudioNode(fileNamed: "Pickle Race theme.m4a")

        addChild(backgroundMusic)

Also, I noticed after I posted there is a missing closure; correcting it obviously didn't help since the code was wrong anyway.

How to dismiss music when game scene exits
 
 
Q