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

前端 未结 1 1770
小蘑菇
小蘑菇 2021-01-24 03:20

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

相关标签:
1条回答
  • 2021-01-24 03:53

    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

    0 讨论(0)
提交回复
热议问题