Search code examples
iosswiftsprite-kitswift2avaudioplayer

iOS+Swift: Why is music not played on iPad?


I am working on a SpriteKit game and trying to play a looped music file. Here's my code:

var musicPlayer = AVAudioPlayer()

override func didMoveToView(view: SKView) {
    self.playBackgroundMusic("gravity")
}

private func playBackgroundMusic(filename: String) {
    do {
        let url = NSBundle.mainBundle().URLForResource(filename, withExtension: "m4a")
        print(url)
        self.musicPlayer = try AVAudioPlayer(contentsOfURL: url!)
        self.musicPlayer.numberOfLoops = -1
        self.musicPlayer.prepareToPlay()
        self.musicPlayer.play()
    } catch let error as NSError {
        print("ERROR: \(error.description)")
    }
}

This works when testing on my iPhone 4S, but not on the iPad Air (there's just no music playing, but works fine with apps like Youtube etc.). Strangely enough, when connecting my Bluetooth head phones to the iPad, it works when listening with the head phones.

My iOS versions are both 9.3.4 for the iPad Air and the iPhone 4S.

Any ideas? Is this a bug on Apple's side ?


Solution

  • Okay I found a fix. Try to call the following code before playing any audio with AVAudioPlayer:

    do {
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord, withOptions: AVAudioSessionCategoryOptions.DefaultToSpeaker)
    } catch let error as NSError {
        print("ERROR: \(error.description)")
    }
    

    Hope this helps somebody.