我正在开发一款包含在后台运行的音频多轨播放器的游戏。当处理暂停所有曲目然后按下暂停按钮时恢复时,我发现没有明显的困难:
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'终止应用程序,原因:'必需条件为false:_engine-> IsRunning()'
所以看起来音频引擎正在停止,我不想因为多种原因重新启动音频播放器,包括设置时间和游戏连续性......
我对这个问题的评估是正确的吗?如果是这样,我如何让音频引擎保持中断或路由更改?
答案 0 :(得分:0)
我不认为这是可能的,因为你为每个声音创建一个音频播放器,它需要准备,设置硬件等。声音完成后,设置将被删除,需要再次完成。即可能无法保持音频引擎“正常运行”。