4
我正在開發一個遊戲,包括在後臺運行的音頻播放器的多軌。當暫停所有曲目,然後按下暫停按鈕時恢復交易,我沒有發現顯著的困難:AVAudioSession中斷和路由變化
class AudioMultiTrack {
var tracks : [AudioTrack]
var mixer : AVAudioMixerNode
var pauseTime : AVAudioTime?
var engine = AVAudioEngine()
var volumes = [Float]()
init(audioTracks: [AudioTrack]){
tracks = audioTracks
mixer = engine.mainMixerNode
}
func initialize() {
for track in tracks {
track.setUpTrack()
engine.attach(track.audioPlayer)
engine.connect(track.audioPlayer, to: mixer, format: track.format)
track.scheduleFile()
}
do {
try engine.start()
} catch {
fatalError("error starting engine")
}
}
func play() {
for track in tracks {
track.audioPlayer.play(at: startTime())
}
}
func pause() {
pauseTime = tracks[0].audioPlayer.lastRenderTime
for track in tracks {
track.audioPlayer.pause()
}
}
func unPause() {
for track in tracks {
track.scheduleFile()
track.audioPlayer.play(at: pauseTime)
}
}
func stop() {
pauseTime = tracks[0].audioPlayer.lastRenderTime
engine.stop()
for track in tracks {
engine.detach(track.audioPlayer)
}
engine.reset()
}
func startTime() ->AVAudioTime {
let sampleRate = tracks[0].format.sampleRate
let sampleTime = AVAudioFramePosition(sampleRate)
return AVAudioTime(sampleTime: sampleTime, atRate: sampleRate)
}
當暫停在GameViewController按:
func pausePressed() {
audio.pause()
}
func continuePressed() {
audio.unPause()
}
然而,當處理以這種方式中斷或路由改變:
func handleInterruption(notification: NSNotification) {
guard let info = notification.userInfo else { return }
switch info[AVAudioSessionInterruptionTypeKey] as! Int {
case 0:
audio.unPause()
case 1:
audio.pause()
default:
break;
}
}
程序崩潰和我接收:
***終止應用程序由於未捕獲的異常「com.apple.coreaudio.avfaudio」,理由是:「要求的條件是假的:_engine-> IsRunning()」
所以它看起來像音頻引擎正在停止,我不想再initalize了許多原因,包括建立時間和玩遊戲的連續性音頻播放器...
我是正確的,我的問題的評價?如果是這樣,我怎樣才能讓音頻引擎在中斷或路由更改的情況下運行?