Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing SKAudioNode using fileNamed returns nil

This is the first time I use SKAudioNode. First I declared a property at the top of my GameScene class:

var backgroundMusic: SKAudioNode!

Now I added a helper method:

func playBackgroundMusic(name: String) {
    if backgroundMusic != nil {
        backgroundMusic.removeFromParent()
    }

    backgroundMusic = SKAudioNode(fileNamed: name)
    backgroundMusic.autoplayLooped = true
    addChild(backgroundMusic)
}

Now I called this method like this:

playBackgroundMusic("ABC.caf")

It throws an fatal error on this line:

backgroundMusic.autoplayLooped = true

Saying: unexpected found nil while unwrapping optional value.

I did make sure the following

  • ABC.caf is in my project and is listed in the copy bundle resources.
  • It is spelled correctly.

Now where else should I check for errors?

EDIT:

Here are my configuration info:

  • Xcode 7.3
  • iPhone with iOS 9.3.2
  • Simulator with iOS 9.3

Both the device and the simulator doesn't work.

EDIT2:

I changed my codes to the following:

func playBackgroundMusic(name: String) {
    if backgroundMusic != nil {
        backgroundMusic.removeFromParent()
    }

    let temp = SKAudioNode(fileNamed: name)
    temp.autoplayLooped = true
    backgroundMusic = temp
    //backgroundMusic = SKAudioNode(fileNamed: "SpaceGame.caf")
    //backgroundMusic.autoplayLooped = true
    addChild(backgroundMusic)
}

Now my app doesn't crash anymore but it has no sounds. Any ideas?

P.S. Few minute after I last edited that question I tried replacing everything in that method with:

runAction(SKAction.playSoundFileNamed(name, waitForCompletion: false))

Still no sound. Perhaps a problem with the sound file?

like image 719
Tom Shen Avatar asked Apr 09 '16 15:04

Tom Shen


2 Answers

I just ran into this issue. Apparently, it only works with local variables now. The below code worked.

var background:SKAudioNode!

override func didMoveToView(view: SKView) {
    let bg = SKAudioNode(fileNamed: "bg.mp3")
    addChild(bg)
    background = bg
}
like image 190
Ryan A. Avatar answered Oct 22 '22 20:10

Ryan A.


I fixed this problem with the code I put in EDIT2 above:

func playBackgroundMusic(name: String) {
    if backgroundMusic != nil {
        backgroundMusic.removeFromParent()
    }

    let temp = SKAudioNode(fileNamed: name)
    temp.autoplayLooped = true
    backgroundMusic = temp
    //backgroundMusic = SKAudioNode(fileNamed: "SpaceGame.caf")
    //backgroundMusic.autoplayLooped = true
    //addChild(backgroundMusic)
    runAction(SKAction.playSoundFileNamed(name, waitForCompletion: false))
}

For the no sound part just make sure the side switch on your iPhone is not on red.

like image 39
Tom Shen Avatar answered Oct 22 '22 19:10

Tom Shen