无法停止游戏场景、Swift 3/Spritekit 中的背景音乐

2023-12-07

在 XCODE 8/Swift 3 和 Spritekit 上,我正在播放背景音乐(一首 5 分钟的歌曲),从 GameViewController 的 ViewDidLoad 调用它(从所有场景的父级,而不是从特定的 GameScene),因为我希望它在整个场景中播放不断变化。发生这种情况是没有问题的。

但我的问题是,当我在场景中时,如何随意停止背景音乐?比如说用户在第三个场景中获得特定分数时?因为我无法访问父文件的方法。这是我用来调用音乐播放的代码:

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

非常感谢您的帮助


为什么不创建一个可以从任何地方访问的音乐助手类。要么是单例方式,要么是带有静态方法的类。这也应该使您的代码更干净且更易于管理。

我还将设置方法和播放方法分开,这样您就不必在每次播放文件时都设置播放器。

例如单例

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

希望这可以帮助

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

无法停止游戏场景、Swift 3/Spritekit 中的背景音乐 的相关文章

随机推荐