i'm playing audio in the background when my app receive voip notification. But AVAudioPlayer acting weird and sometimes play the audio and sometimes not without any error. thats how i play:
func playAudio() {
// Set the sound file name & extension
let alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("testAudio", ofType: "wav")!)
// Play the sound
do {
try audioPlayer = AVAudioPlayer(contentsOfURL: alertSound)
audioPlayer.delegate = self
if (audioPlayer.prepareToPlay()) {
audioPlayer.play()
}
else {NSLog("there is error")}
} catch {
NSLog("there is \(error)")
}
}
I initialize AVAudioSession in my AppDelegate application function:
do
{
audioPlayer = AVAudioPlayer()
audioSession = AVAudioSession()
try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord, withOptions: [AVAudioSessionCategoryOptions.MixWithOthers])
try audioSession.setActive(true)
try audioSession.overrideOutputAudioPort(AVAudioSessionPortOverride.Speaker)
}
catch {
NSLog("there is \(error)")
}
and of course var audioPlayer: AVAudioPlayer!
as a class verb
Its working for the first minute or two and then AVAudioPlayer stop responding without any error. I even try to use AVAudioPlayerDelegate to receive events, but nothing happen.
can someone explain this behavior? is it a bug in ios? or i'm doing somthing wrong? tested on Ios 9.2, iphone 6 device, xcode 7.2.
Thanks.