如何停止SKAction背景音乐

How stop SKAction background music

我正在尝试制作游戏,在主菜单中,有一个标签用于开始音乐,另一个用于停止音乐。

let backgroundMusic = SKAction.playSoundFileNamed("background.mp3", waitForCompletion: false)

 override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches {
            let location = touch.location(in: self)
            let touchedNode = atPoint(location)
            if touchedNode.name == self.BEGIN_MUSIC {
                // start music
                self.run(backgroundMusic)
            }
            if touchedNode.name == self.STOP_MUSIC {
                // stop music
                SKAction.stop()
            }
        }
    }

音乐开始很好,适用于我想要的所有场景。但是当我按下停止音乐时,音乐会继续播放。如何停止音乐。

我试过 SKAction.pause(),我试过使用 withKey: "music" 然后 self.removeAction(forKey: "music")。

我也试过制作 backgroundMusic: SKAudioNode,这很有效,但是一旦我停止了音乐,我就无法重新打开它,而且它在任何其他场景中都不起作用,只有主菜单。

如何停止声音?

我刚才遇到了同样的问题:这就是我让它工作的方式。这是特定于背景音乐。

   var backgroundMusic: AVAudioPlayer!


   func playMusic() {
      if let musicURL = Bundle.main.url(forResource: "musicSource", withExtension: "wav") {
          if let audioPlayer = try? AVAudioPlayer(contentsOf: musicURL) {
              backgroundMusic = audioPlayer
              backgroundMusic.numberOfLoops = -1
              backgroundMusic.play()
              backgroundMusic.volume = 0.2
            
          }    
      }
   }


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

      if let touch = touches.first {
          let pos = touch.location(in: self)
          let node = self.atPoint(pos)

       let musicOff = UserDefaults.standard.bool(forKey: "musicOff")

       if node == musicButton && musicOff == false {

               backgroundMusic.stop()
               UserDefaults.standard.set(true, forKey: "musicOff")

       }

       if node == musicButton && musicOff == true {

                backgroundMusic.play()
                backgroundMusic.volume = 0.3
                UserDefaults.standard.set(false, forKey: "musicOff")

       }
     }
   }