0

我最后的游戏结束场景有一个 SKTransition 回到主菜单。我可以为最终的游戏结束场景制作一首歌曲,但我希望这首歌继续出现在我的主菜单中。

这是我目前拥有的代码的副本。

import Foundation
import SpriteKit
import AVFoundation


class SceneThree: SKScene {

   var game = SKSpriteNode()

var new: AVAudioPlayer?

override func didMove(to view: SKView) {

    self.backgroundColor = SKColor.black

    playSound()

}

func playSound() {
    let url = Bundle.main.url(forResource: "new", withExtension: "caf")!

    do {
        new = try AVAudioPlayer(contentsOf: url)
        guard let new = new else { return }

        new.prepareToPlay()
        new.play()
    } catch let error {
        print(error.localizedDescription)
    }
}



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

    let gameScene = GameScene(fileNamed: "GameScene")
    gameScene?.scaleMode = .aspectFill
    self.view?.presentScene(gameScene!, transition: SKTransition.fade(withDuration: 4.5))



}
4

1 回答 1

0

当您更改场景时,旧场景将被销毁,其中包括您的 AVPlayer 属性。

您可以为您的音乐创建一个助手类来避免这种情况。

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()
    }
}

当您的项目启动时,只需调用 setup 方法

MusicManager.shared.setup()

比您项目中的任何地方都可以说

MusicManager.shared.play()

播放音乐。

要停止它只需调用停止方法

MusicManager.shared.stop()

有关具有多个轨道的功能更丰富的示例,请查看我在 GitHub 上的帮助程序

https://github.com/crashoverride777/SwiftyMusic

希望这可以帮助

于 2016-12-09T19:03:36.350 回答