我在场景中的最后一场比赛将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))
}
答案 0 :(得分: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()
}
}
当您的项目启动时,只需调用设置方法
MusicManager.shared.setup()
比您项目中的任何地方都可以说
MusicManager.shared.play()
播放音乐。
要停止它,只需调用stop方法
MusicManager.shared.stop()
有关具有多个曲目的功能更丰富的示例,请在GitHub上查看我的助手
https://github.com/crashoverride777/SwiftyMusic
希望这有帮助