首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法阻止游戏场景中的背景音乐,Swift 3/Spritekit

无法阻止游戏场景中的背景音乐,Swift 3/Spritekit
EN

Stack Overflow用户
提问于 2016-10-28 01:53:04
回答 1查看 794关注 0票数 1

在XCODE 8/Swift 3和Spritekit上,我正在播放背景音乐(5分钟的歌曲),从GameViewController的ViewDidLoad (来自所有场景的父场景,而不是特定的GameScene)调用它,因为我希望它在整个场景更改过程中不间断地播放。这是没有问题的。

但我的问题是,当我在一个场景中时,我如何随心所欲地停止背景音乐呢?比如说,当用户在第三场比赛中得到一个特定的分数时?因为我不能访问父文件的方法。下面是我用来调用音乐播放的代码:

类GameViewController: UIViewController {

代码语言:javascript
复制
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()

非常感谢你的帮助

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-11-01 13:51:06

为什么不创建一个可以从任何地方访问的音乐助手类呢?单例方法或具有静态方法的类。这也会使您的代码更简洁、更易于管理。

我还会拆分安装方法和play方法,这样每次播放文件时都不会设置播放机。

例如,辛格尔顿

代码语言:javascript
复制
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()
    }
}

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

代码语言:javascript
复制
MusicManager.shared.setup()

在你的项目中任何地方你都可以说

代码语言:javascript
复制
MusicManager.shared.play()

去演奏音乐。

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

代码语言:javascript
复制
MusicManager.shared.stop()

要获得更多功能丰富的多声道示例,请查看GitHub上的“我的助手”

https://github.com/crashoverride777/SwiftyMusic

希望这能有所帮助

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40296793

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档