SKAudioNode() crashes when plugging in/out headphones

雨燕双飞 提交于 2019-12-04 02:29:58

I was not able fix it, but by using AVAudioPlayer() I found a good workaround. Thank you all for supporting me!

import SpriteKit
import AVFoundation

class GameScene: SKScene {    
    var audioPlayer = AVAudioPlayer()  

    override func didMoveToView(view: SKView) {        
        initAudioPlayer("gameloop.mp3")        
    }

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {        
        _ = touches.first as UITouch!
        for _ in touches {
            toggleBackgroundMusic()            
        }        
    }

    func initAudioPlayer(filename: String) {        
        let url = NSBundle.mainBundle().URLForResource(filename, withExtension: nil)
        guard let newURL = url else {
            print("Could not find file: \(filename)")
            return
        }
        do {
            audioPlayer = try AVAudioPlayer(contentsOfURL: newURL)
            audioPlayer.numberOfLoops = -1
            audioPlayer.prepareToPlay()
            audioPlayer.play()
        } catch let error as NSError {
            print(error.description)
        }        
    }

    func toggleBackgroundMusic() {        
        if audioPlayer.playing {
            audioPlayer.pause()
        } else {
            audioPlayer.play()
        }        
    }    
}

SKScene has a property named audioEngine that is stopped in certain circumstances. If you´re using ReplayKit for example, playing a recorded gameplay movie in the RPPreviewController hi-jacks the audio and stops it, so when you dismiss it, the audioEngine is no longer running.

I had this issue and solved it by doing a simple check and starting the audioEngine again. Try this:

if !self.audioEngine.isRunning {
    do {
        try self.audioEngine.start()
    } catch {
        //handle error
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!