Cannot stop background music from within Game Scenes, Swift 3/Spritekit

白昼怎懂夜的黑 提交于 2019-12-20 07:22:06

问题


On XCODE 8/Swift 3 and Spritekit, i am playing background music (a 5 minute song), calling it from GameViewController's ViewDidLoad (from the parent of all the scenes, not from a specific GameScene), as I want it to play throughout scene changes without stopping. This happens without a problem.

But my problem is, how do i stop the background music at will, when I am inside a scene? Say when user gets to a specific score on the game on the 3rd scene? As i cannot access the methods of the parent file. Here is the code I used to call the music to play:

class GameViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    var audioPlayer = AVAudioPlayer()

    do {
        audioPlayer =  try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "music", ofType: "mp3")!))
        audioPlayer.prepareToPlay()

    } catch {

        print (error)
    }
    audioPlayer.play()

Many thanks for any help


回答1:


Why not create a music helper class that you can access from anywhere. Either the singleton way or a class with static methods. This should also make your code cleaner and easier to manage.

I would also split the setup method and the play method so that you do not set up the player each time you play the file.

e.g Singleton

class MusicManager {

    static let shared = MusicManager()

    var audioPlayer = AVAudioPlayer()


    private init() { } // private singleton init


    func setup() {
         do {
            audioPlayer =  try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "music", ofType: "mp3")!))
             audioPlayer.prepareToPlay()

        } catch {
           print (error)
        }
    }


    func play() {
        audioPlayer.play()
    }

    func stop() {
        audioPlayer.stop()
        audioPlayer.currentTime = 0 // I usually reset the song when I stop it. To pause it create another method and call the pause() method on the audioPlayer.
        audioPlayer.prepareToPlay()
    }
}

When your project launches just call the setup method

MusicManager.shared.setup()

Than from any where in your project you can say

MusicManager.shared.play()

to play the music.

To than stop it just call the stop method

MusicManager.shared.stop()

For a more feature rich example with multiple tracks check out my helper on GitHub

https://github.com/crashoverride777/SwiftyMusic

Hope this helps



来源:https://stackoverflow.com/questions/40296793/cannot-stop-background-music-from-within-game-scenes-swift-3-spritekit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!