0

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.

omer katz
  • 1
  • 1
  • 1
    Did you turn on "Background Modes" in the "Capabilities"? – Allen Feb 06 '16 at 01:16
  • @Allen yes, and then check off "Audio, Airplay...etc" – MikeG Feb 06 '16 at 01:35
  • Try creating the AVAudioPlayer once and then just using it when in the background. When you move to the background you are allowed to do work for a little while and it may be that you are allowed to create the player. After that the rules change and what you can do is more limited. – Gary Makin Feb 06 '16 at 03:06
  • Perhaps increasing the scope of `audioPlayer`? – MikeG Feb 06 '16 at 04:03
  • Yes i turned on "background modes" and checked the audio. What do you mean by increasing the scop of audioPlayer? Do you know where i can find the rules that i can do in the background? And if so how other voip apps works and always play the tone in the background? – omer katz Feb 07 '16 at 17:50
  • You can find the rules for what you can do in the background [here](https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html). What i meant by increasing the scope was moving it to a "higher" level where it will persist beyond the scope of a single function or class. But I think I am wrong since you have it in App delegate – MikeG Feb 08 '16 at 01:41

0 Answers0