音乐停止播放后场景改变SKAudioNode Xcode 8

时间:2017-02-13 16:01:17

标签: ios xcode sprite-kit

所以我一直试图让这个音频文件在游戏的所有场景中播放,但它在MenuScene之后被切断了。我从MenuScene

致电GameViewController
class GameViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    if let view = self.view as! SKView? {
        // Load the SKScene from 'MenuScene.sks'
        if let scene = SKScene(fileNamed: "MenuScene") {
            // Set the scale mode to scale to fit the window

然后在MenuScene中,我通过这样做来启动音乐。

class MenuScene: SKScene {

var starfield:SKEmitterNode!

var newGameButtonNode:SKSpriteNode!
var difficultyButtonNode:SKSpriteNode!
var difficultyLabelNode:SKLabelNode!
var backgroundMusic:SKAudioNode!

override func didMove(to view: SKView) {


    let backgroundMusic = SKAudioNode(fileNamed: "Snap.mp3")
    backgroundMusic.autoplayLooped = true
    addChild(backgroundMusic)

音乐开始播放。然后我在touchesBegan ()中,如果触摸了GameScene按钮,它将加载该场景。我进行了很长时间的转换,以找出音乐何时停止并且在整个过渡期间播放,但是当GameScene加载时它停止。

if nodesArray.first?.name == "newGameButton" {

            let transition = SKTransition.fade(withDuration: 5.0)

            run(SKAction.wait(forDuration: 5.0), completion: {
                self.backgroundMusic = SKAudioNode(fileNamed: "Snap.mp3")
                self.backgroundMusic.autoplayLooped = true
                self.addChild(self.backgroundMusic)
            })
            let gameScene = GameScene(size: self.size)

            self.view!.presentScene(gameScene, transition: transition)

我希望它能够在整个游戏和GameOver场景中继续播放并永远循环播放。

1 个答案:

答案 0 :(得分:1)

确保您的主要SKScene和

您可以这样做:

self.runAction(SKAction.playSoundFileNamed("YourFileName.extension", waitForCompletion: false))

重复音乐:

SKAction.repeatForever(SKAction.playSoundFileNamed("YourFileName.extension", waitForCompletion: true))

你的音乐将继续播放..

  

使用AVFoundation

我做过的一个代码。

import AVFoundation


var backgroundMusicPlayer: AVAudioPlayer!

func playBackgroundMusic(filename: String) {
let url = NSBundle.mainBundle().URLForResource(
filename, withExtension: nil)
if (url == nil) {
print("Could not find file: \(filename)")
return
}

var error: NSError? = nil
backgroundMusicPlayer = 
AVAudioPlayer(contentsOfURL: url, error: &error)
if backgroundMusicPlayer == nil {
print("Could not create audio player: \(error!)")
return
}

backgroundMusicPlayer.numberOfLoops = -1
backgroundMusicPlayer.prepareToPlay()
backgroundMusicPlayer.play()
 }

  import SpriteKit