SKAudioNode()在插拔耳机时会崩溃

12

我在我的游戏中使用SKAudioNode()播放背景音乐。 我有一个播放/暂停函数,一切正常,直到我插上耳机。 没有任何声音,当我调用暂停/播放功能时,我会收到以下错误消息:

AVAudioPlayerNode.mm:333: Start: required condition is false: _engine->IsRunning() com.apple.coreaudio.avfaudio', reason: 'required condition is false: _engine->IsRunning()

有人知道这是什么意思吗?

代码:

import SpriteKit

class GameScene: SKScene {

let loop = SKAudioNode(fileNamed: "gameloop.mp3")
let play = SKAction.play()
let pause = SKAction.pause()
var isPlaying = Bool()

override func didMoveToView(view: SKView) {  
    loop.runAction(play)
    isPlaying = true
    self.addChild(loop)
}

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

    for _ in touches {
        if isPlaying {
            loop.runAction(pause)
            isPlaying = false
        } else {
            loop.runAction(play)
            isPlaying = true
        } 
    }
}
}

可能是AVAudioEngine插入或拔出耳机时崩溃的重复问题。 - Chris Slowik
AVAudioEngineConfigurationChangeNotification对我没有帮助:(我在找到那个问题之前就已经这样认为了。 - Cherrypig
你能解释一下你的操作顺序吗?是先启动应用,然后播放音乐,再插入耳机,最后点击屏幕导致崩溃吗? - Knight0fDragon
@Cherrypig 真遗憾SKAudioNode目前是这样的状况。但我仍然希望(希望最后不会熄灭哈哈),有解决方法,并且我想在这个问题上开始一个赏金。到目前为止,它只被浏览了34次,我只是想再给它一次机会。如果您同意,请告诉我。 - Whirlwind
1
@Whirlwind 这将会很棒!谢谢。希望有人知道解决方案 :) - Cherrypig
显示剩余11条评论
2个回答

2

我没有能够修复它,但是通过使用AVAudioPlayer(),我找到了一个很好的解决办法。谢谢大家的支持!

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()
        }        
    }    
}

2

SKScene有一个名为audioEngine的属性,在某些情况下会停止。例如,如果您正在使用ReplayKit,在RPPreviewController中播放录制的游戏过程视频会中断音频并停止它,因此当您关闭它时,audioEngine将不再运行。

我曾经遇到这个问题,并通过进行简单的检查并重新启动audioEngine来解决它。请尝试以下方法:

if !self.audioEngine.isRunning {
    do {
        try self.audioEngine.start()
    } catch {
        //handle error
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接