【问题标题】:Cannot stop background music from within Game Scenes, Swift 3/Spritekit无法从游戏场景中停止背景音乐,Swift 3/Spritekit
【发布时间】:2016-10-28 01:53:04
【问题描述】:

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

非常感谢您的帮助

【问题讨论】:

    标签: swift xcode avfoundation avaudioplayer


    【解决方案1】:

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

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

    例如单例

    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

    希望对你有帮助

    【讨论】:

    • 非常感谢 - 我会试试这个
    • 你过得怎么样?
    • 嗨@crashoverride777 - 不幸的是,我一直非常忙于应用程序的其他部分以恢复这一点,一旦我设法做到这一点,我会告诉你的。再次感谢!
    猜你喜欢
    • 1970-01-01
    • 2016-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多