Swift 2 Spritekit:当游戏取消暂停时,背景音乐无法恢复的问题

时间:2016-06-16 19:50:38

标签: xcode swift sprite-kit

首先,我想提前感谢任何人提供任何帮助。

我在网上搜索得很远,无法找到解决问题的方法。我的问题是我正在使用SpriteKit框架构建的iOS游戏。我使用SKAudioNode添加了一首背景歌曲,它最初工作正常,但是当我暂停并在几秒钟内播放游戏时,音乐不再开始播放。我已经尝试了很多东西,例如在游戏暂停时移除SKAudioNode并在游戏恢复时再次添加它,但没有任何效果。我在下面发布了一段我的代码,尽可能保持相关性:

 class GameScene: SKScene, SKPhysicsContactDelegate {
    var backgroundMusic = SKAudioNode(fileNamed: "bg.mp3")    
    let pauseImage = SKTexture(imageNamed: "pause.png")
    var pauseButton:SKSpriteNode!
    let playImage = SKTexture(imageNamed: "play2.png")
    var playButton:SKSpriteNode!

    override func didMoveToView(view: SKView) {
        self.addChild(backgroundMusic)

        // create pause button
        pauseButton = SKSpriteNode(texture: pauseImage)
        pauseButton.position = CGPoint(x: self.size.width - pauseButton.size.width, y: pauseButton.size.height)
        pauseButton.zPosition = 1
        pauseButton.name = "pauseButton"
        self.addChild(pauseButton)

        // create play button
        playButton = SKSpriteNode(texture: playImage)
        playButton.position = CGPoint(x: self.size.width - playButton.size.width, y: -playButton.size.height)
        playButton.zPosition = 1
        playButton.name = "playButton"
        self.addChild(playButton)
    }

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        for touch in touches {
            if pauseButton.containsPoint(touch.locationInNode(self)) {
                let blockOne = SKAction.runBlock({
                    self.pauseButton.position.y = -     self.pauseButton.size.height
                    self.playButton.position.y = self.playButton.size.height
                })

                let blockTwo = SKAction.runBlock({
                    self.view?.paused = true
                })

                self.runAction(SKAction.sequence([blockOne, blockTwo]))
            }
            else if(playButton.containsPoint(touch.locationInNode(self))) {
                self.playButton.position.y = -self.playButton.size.height
                self.pauseButton.position.y = self.pauseButton.size.height
                self.view?.paused = false
            }
        }
    }
}

1 个答案:

答案 0 :(得分:2)

您希望了解如何使用AVAudioPlayer和NSNotificationCenter在游戏中传递数据。

在实际的GameViewController类中启动背景音频播放器。 用这种方式做得更好然后使用SKAudioNode ......对于那些与游戏中发生的事情有关的声音效果的声音更多。

通过使用AVAudioPlayer,优点是当音乐暂停时,它仍然可以在其前一个位置播放。

无论发生什么事情,这都是为数不多的事情之一。所以我们把它放在GameViewController中。

所以这是我们需要启动的GameViewController代码示例

import AVFoundation

var bgMusicPlayer:AVAudioPlayer?

然后在GameViewController中我们将这些函数作为这样的

override func viewDidLoad() {



super.viewDidLoad()


// PlayBackgroundSound  , PauseBackgroundSound will be your code to send from other "scenes" to use the audio player //

// NSNotificationCenter to pass data throughout the game //

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(GameViewController.playBackgroundSound(_:)), name: "PlayBackgroundSound", object: nil)



NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(GameViewController.pauseBackgroundSound), name: "PauseBackgroundSound", object: nil)

 }

func playBackgroundSound(notification: NSNotification) {


let name = notification.userInfo!["fileToPlay"] as! String



if (bgSoundPlayer != nil){

    bgSoundPlayer!.stop()
    bgSoundPlayer = nil


}

if (name != ""){

    let fileURL:NSURL = NSBundle.mainBundle().URLForResource(name, withExtension: "mp3")!

    do {
        bgSoundPlayer = try AVAudioPlayer(contentsOfURL: fileURL)
    } catch _{
        bgSoundPlayer = nil

    }

    bgSoundPlayer!.volume = 1
    bgSoundPlayer!.numberOfLoops = -1

// -1 will loop it forever // 

    bgSoundPlayer!.prepareToPlay()
    bgSoundPlayer!.play()

   }
 }


func pauseBackgroundSound() {

    if (bgSoundPlayer != nil){

        bgSoundPlayer!.pause()



    }

}

然后当你想在暂停或恢复按钮功能中使用音频播放器时。

请记住,您需要在每个场景中使用播放器。

 import AVFoundation.AVAudioSession

 override func didMoveToView(view: SKView) {

     try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)

}

然后,如果您想暂停或播放某些内容,请使用NSNotificationCenter。

//要在场景中暂停,请在暂停音乐所需的功能中使用此行代码

NSNotificationCenter.defaultCenter().postNotificationName("PauseBackgroundSound", object: self)

///最初播放或新歌..在播放音乐所需的功能中使用此行代码

NSNotificationCenter.defaultCenter().postNotificationName("PlayBackgroundSound", object: self, userInfo: "FILE NAME OF BACKGROUND MUSIC")