How to resume background audio in Swift 2 / AVPlayer?












8














I am learning Swift as my first programming language.



I've struggled for many hours to resume background audio playback after interruption (eg call)



What should happen:




  1. Audio keeps playing when app goes to background (works)

  2. When interrupted by a call, get the notification for interruption began
    (works)

  3. When call ends, get the notification for interruption
    ends (works)

  4. Resume playing the audio (does NOT work - hear nothing)


Really appreciate any help! Thanks



Notes:




  1. The app is registered for background audio and plays fine before interruption

  2. I have tried with and without the time delay to resume playing - neither work


Code:



import UIKit
import AVFoundation

var player: AVQueuePlayer!

class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true, withOptions: .NotifyOthersOnDeactivation)
} catch { }
let songNames = ["music"]
let songs = songNames.map { AVPlayerItem(URL:
NSBundle.mainBundle().URLForResource($0, withExtension: "mp3")!) }
player = AVQueuePlayer(items: songs)

let theSession = AVAudioSession.sharedInstance()
NSNotificationCenter.defaultCenter().addObserver(self,
selector:"playInterrupt:",
name:AVAudioSessionInterruptionNotification,
object: theSession)

player.play()
}

func playInterrupt(notification: NSNotification) {

if notification.name == AVAudioSessionInterruptionNotification
&& notification.userInfo != nil {

var info = notification.userInfo!
var intValue: UInt = 0
(info[AVAudioSessionInterruptionTypeKey] as! NSValue).getValue(&intValue)
if let type = AVAudioSessionInterruptionType(rawValue: intValue) {
switch type {
case .Began:
print("aaaaarrrrgggg you stole me")
player.pause()

case .Ended:
let timer = NSTimer.scheduledTimerWithTimeInterval(3, target: self, selector: "resumeNow:", userInfo: nil, repeats: false)
}
}
}
}
func resumeNow(timer : NSTimer) {
player.play()
print("attempted restart")
}
}









share|improve this question
























  • Does the methods are properly called? especially the resumeNow method.
    – Jason Nam
    Sep 13 '15 at 9:37










  • Yes - I see the log showing "attempted restart" 3 seconds after the call is terminated.
    – Simon Newstead
    Sep 13 '15 at 9:39
















8














I am learning Swift as my first programming language.



I've struggled for many hours to resume background audio playback after interruption (eg call)



What should happen:




  1. Audio keeps playing when app goes to background (works)

  2. When interrupted by a call, get the notification for interruption began
    (works)

  3. When call ends, get the notification for interruption
    ends (works)

  4. Resume playing the audio (does NOT work - hear nothing)


Really appreciate any help! Thanks



Notes:




  1. The app is registered for background audio and plays fine before interruption

  2. I have tried with and without the time delay to resume playing - neither work


Code:



import UIKit
import AVFoundation

var player: AVQueuePlayer!

class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true, withOptions: .NotifyOthersOnDeactivation)
} catch { }
let songNames = ["music"]
let songs = songNames.map { AVPlayerItem(URL:
NSBundle.mainBundle().URLForResource($0, withExtension: "mp3")!) }
player = AVQueuePlayer(items: songs)

let theSession = AVAudioSession.sharedInstance()
NSNotificationCenter.defaultCenter().addObserver(self,
selector:"playInterrupt:",
name:AVAudioSessionInterruptionNotification,
object: theSession)

player.play()
}

func playInterrupt(notification: NSNotification) {

if notification.name == AVAudioSessionInterruptionNotification
&& notification.userInfo != nil {

var info = notification.userInfo!
var intValue: UInt = 0
(info[AVAudioSessionInterruptionTypeKey] as! NSValue).getValue(&intValue)
if let type = AVAudioSessionInterruptionType(rawValue: intValue) {
switch type {
case .Began:
print("aaaaarrrrgggg you stole me")
player.pause()

case .Ended:
let timer = NSTimer.scheduledTimerWithTimeInterval(3, target: self, selector: "resumeNow:", userInfo: nil, repeats: false)
}
}
}
}
func resumeNow(timer : NSTimer) {
player.play()
print("attempted restart")
}
}









share|improve this question
























  • Does the methods are properly called? especially the resumeNow method.
    – Jason Nam
    Sep 13 '15 at 9:37










  • Yes - I see the log showing "attempted restart" 3 seconds after the call is terminated.
    – Simon Newstead
    Sep 13 '15 at 9:39














8












8








8


9





I am learning Swift as my first programming language.



I've struggled for many hours to resume background audio playback after interruption (eg call)



What should happen:




  1. Audio keeps playing when app goes to background (works)

  2. When interrupted by a call, get the notification for interruption began
    (works)

  3. When call ends, get the notification for interruption
    ends (works)

  4. Resume playing the audio (does NOT work - hear nothing)


Really appreciate any help! Thanks



Notes:




  1. The app is registered for background audio and plays fine before interruption

  2. I have tried with and without the time delay to resume playing - neither work


Code:



import UIKit
import AVFoundation

var player: AVQueuePlayer!

class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true, withOptions: .NotifyOthersOnDeactivation)
} catch { }
let songNames = ["music"]
let songs = songNames.map { AVPlayerItem(URL:
NSBundle.mainBundle().URLForResource($0, withExtension: "mp3")!) }
player = AVQueuePlayer(items: songs)

let theSession = AVAudioSession.sharedInstance()
NSNotificationCenter.defaultCenter().addObserver(self,
selector:"playInterrupt:",
name:AVAudioSessionInterruptionNotification,
object: theSession)

player.play()
}

func playInterrupt(notification: NSNotification) {

if notification.name == AVAudioSessionInterruptionNotification
&& notification.userInfo != nil {

var info = notification.userInfo!
var intValue: UInt = 0
(info[AVAudioSessionInterruptionTypeKey] as! NSValue).getValue(&intValue)
if let type = AVAudioSessionInterruptionType(rawValue: intValue) {
switch type {
case .Began:
print("aaaaarrrrgggg you stole me")
player.pause()

case .Ended:
let timer = NSTimer.scheduledTimerWithTimeInterval(3, target: self, selector: "resumeNow:", userInfo: nil, repeats: false)
}
}
}
}
func resumeNow(timer : NSTimer) {
player.play()
print("attempted restart")
}
}









share|improve this question















I am learning Swift as my first programming language.



I've struggled for many hours to resume background audio playback after interruption (eg call)



What should happen:




  1. Audio keeps playing when app goes to background (works)

  2. When interrupted by a call, get the notification for interruption began
    (works)

  3. When call ends, get the notification for interruption
    ends (works)

  4. Resume playing the audio (does NOT work - hear nothing)


Really appreciate any help! Thanks



Notes:




  1. The app is registered for background audio and plays fine before interruption

  2. I have tried with and without the time delay to resume playing - neither work


Code:



import UIKit
import AVFoundation

var player: AVQueuePlayer!

class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true, withOptions: .NotifyOthersOnDeactivation)
} catch { }
let songNames = ["music"]
let songs = songNames.map { AVPlayerItem(URL:
NSBundle.mainBundle().URLForResource($0, withExtension: "mp3")!) }
player = AVQueuePlayer(items: songs)

let theSession = AVAudioSession.sharedInstance()
NSNotificationCenter.defaultCenter().addObserver(self,
selector:"playInterrupt:",
name:AVAudioSessionInterruptionNotification,
object: theSession)

player.play()
}

func playInterrupt(notification: NSNotification) {

if notification.name == AVAudioSessionInterruptionNotification
&& notification.userInfo != nil {

var info = notification.userInfo!
var intValue: UInt = 0
(info[AVAudioSessionInterruptionTypeKey] as! NSValue).getValue(&intValue)
if let type = AVAudioSessionInterruptionType(rawValue: intValue) {
switch type {
case .Began:
print("aaaaarrrrgggg you stole me")
player.pause()

case .Ended:
let timer = NSTimer.scheduledTimerWithTimeInterval(3, target: self, selector: "resumeNow:", userInfo: nil, repeats: false)
}
}
}
}
func resumeNow(timer : NSTimer) {
player.play()
print("attempted restart")
}
}






ios swift audio avfoundation avplayer






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Sep 13 '15 at 9:47







Simon Newstead

















asked Sep 13 '15 at 9:29









Simon NewsteadSimon Newstead

180216




180216












  • Does the methods are properly called? especially the resumeNow method.
    – Jason Nam
    Sep 13 '15 at 9:37










  • Yes - I see the log showing "attempted restart" 3 seconds after the call is terminated.
    – Simon Newstead
    Sep 13 '15 at 9:39


















  • Does the methods are properly called? especially the resumeNow method.
    – Jason Nam
    Sep 13 '15 at 9:37










  • Yes - I see the log showing "attempted restart" 3 seconds after the call is terminated.
    – Simon Newstead
    Sep 13 '15 at 9:39
















Does the methods are properly called? especially the resumeNow method.
– Jason Nam
Sep 13 '15 at 9:37




Does the methods are properly called? especially the resumeNow method.
– Jason Nam
Sep 13 '15 at 9:37












Yes - I see the log showing "attempted restart" 3 seconds after the call is terminated.
– Simon Newstead
Sep 13 '15 at 9:39




Yes - I see the log showing "attempted restart" 3 seconds after the call is terminated.
– Simon Newstead
Sep 13 '15 at 9:39












4 Answers
4






active

oldest

votes


















4














Finally got it!



Solution: added the mixable option by changing the setCategory line to be:



AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback,
withOptions: .mixWithOthers )





share|improve this answer































    1














    I wrote a code like this and successfully resumed the audio from the phone call ended. I was build on Xcode 6.4 and ran the app on my iPhone 4S.



    var player: AVQueuePlayer! = nil

    override func viewDidLoad()
    {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    }

    override func viewDidAppear(animated: Bool)
    {
    super.viewDidAppear(true)

    var song = AVPlayerItem(URL: NSBundle.mainBundle().URLForResource("AlmostAYearAgo", withExtension: "mp3")!)
    player = AVQueuePlayer(items: [song])

    let theSession = AVAudioSession.sharedInstance()

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "playInterrupt:", name: AVAudioSessionInterruptionNotification, object: theSession)

    player.play()
    }

    override func didReceiveMemoryWarning()
    {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
    }

    func playInterrupt(notification: NSNotification)
    {
    if notification.name == AVAudioSessionInterruptionNotification && notification.userInfo != nil
    {
    var info = notification.userInfo!
    var intValue: UInt = 0

    (info[AVAudioSessionInterruptionTypeKey] as! NSValue).getValue(&intValue)

    if let type = AVAudioSessionInterruptionType(rawValue: intValue)
    {
    switch type
    {
    case .Began:
    print("aaaaarrrrgggg you stole me")
    player.pause()
    case .Ended:
    let timer = NSTimer.scheduledTimerWithTimeInterval(3, target: self, selector: "resumeNow:", userInfo: nil, repeats: false)
    }
    }
    }
    }

    func resumeNow(timer : NSTimer)
    {
    player.play()
    print("attempted restart")
    }





    share|improve this answer























    • Tried it, but doesn't seem to do anything. Audio still doesn't play on resume.
      – Simon Newstead
      Sep 13 '15 at 9:57










    • Where did you put the code?
      – Jason Nam
      Sep 13 '15 at 9:57










    • in both: case .Ended and in resumeNow just before player.play() have you managed to get it working?
      – Simon Newstead
      Sep 13 '15 at 10:00










    • Check this answers stackoverflow.com/questions/12461691/…
      – Jason Nam
      Sep 13 '15 at 10:16










    • Hi Jason thanks but that doesn't seem to help solve the problem (and was from a long while ago - can I see where it's been fixed or documented?)
      – Simon Newstead
      Sep 14 '15 at 3:05



















    0














    For me reload player after end interruption resolve the problem:



        func interruptionNotification(_ notification: Notification) {
    guard let type = notification.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt,
    let interruption = AVAudioSessionInterruptionType(rawValue: type) else {
    return
    }
    if interruption == .ended && playerWasPlayingBeforeInterruption {
    player.replaceCurrentItem(with: AVPlayerItem(url: radioStation.url))
    play()
    }
    }





    share|improve this answer





























      -1














      Simon, absolutely confirm it on my end. I spend 2 days looking for it! If you use just:



      AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) then does not matter what you do your player will not resume playing audio if you use instead:



      AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, withOptions: AVAudioSessionCategoryOptions.MixWithOthers)



      then it works like perfect and will resume after receiving phone call while the app is in the background.



      Thanks!






      share|improve this answer





















      • Simon, not sure if you noticed but this is not the working solution. I thought the solution was working but when you use: AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, withOptions: AVAudioSessionCategoryOptions.MixWithOthers then your player will mix with others. Try staring music app as well in the same time. You will get 2 sounds playing at the same time and mixing. It works for resuming after the call while in the background but it messes up the whole playback of your sound. Anyone any idea please?
        – aurawindsurfing
        Sep 19 '15 at 10:05












      • The thing that we were missing was self.becomeFirstResponder() once that was added the whole thing started to work for me.
        – aurawindsurfing
        Sep 19 '15 at 17:16










      • Good to know, thanks. I don't need it because my app is a silent meditation app and they won't mix audio themselves, so hadn't tested that option.
        – Simon Newstead
        Sep 21 '15 at 7:37











      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f32548236%2fhow-to-resume-background-audio-in-swift-2-avplayer%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      4 Answers
      4






      active

      oldest

      votes








      4 Answers
      4






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      4














      Finally got it!



      Solution: added the mixable option by changing the setCategory line to be:



      AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback,
      withOptions: .mixWithOthers )





      share|improve this answer




























        4














        Finally got it!



        Solution: added the mixable option by changing the setCategory line to be:



        AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback,
        withOptions: .mixWithOthers )





        share|improve this answer


























          4












          4








          4






          Finally got it!



          Solution: added the mixable option by changing the setCategory line to be:



          AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback,
          withOptions: .mixWithOthers )





          share|improve this answer














          Finally got it!



          Solution: added the mixable option by changing the setCategory line to be:



          AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback,
          withOptions: .mixWithOthers )






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 21 '18 at 19:25









          Paul Nyondo

          68821019




          68821019










          answered Sep 17 '15 at 16:09









          Simon NewsteadSimon Newstead

          180216




          180216

























              1














              I wrote a code like this and successfully resumed the audio from the phone call ended. I was build on Xcode 6.4 and ran the app on my iPhone 4S.



              var player: AVQueuePlayer! = nil

              override func viewDidLoad()
              {
              super.viewDidLoad()
              // Do any additional setup after loading the view, typically from a nib.
              }

              override func viewDidAppear(animated: Bool)
              {
              super.viewDidAppear(true)

              var song = AVPlayerItem(URL: NSBundle.mainBundle().URLForResource("AlmostAYearAgo", withExtension: "mp3")!)
              player = AVQueuePlayer(items: [song])

              let theSession = AVAudioSession.sharedInstance()

              NSNotificationCenter.defaultCenter().addObserver(self, selector: "playInterrupt:", name: AVAudioSessionInterruptionNotification, object: theSession)

              player.play()
              }

              override func didReceiveMemoryWarning()
              {
              super.didReceiveMemoryWarning()
              // Dispose of any resources that can be recreated.
              }

              func playInterrupt(notification: NSNotification)
              {
              if notification.name == AVAudioSessionInterruptionNotification && notification.userInfo != nil
              {
              var info = notification.userInfo!
              var intValue: UInt = 0

              (info[AVAudioSessionInterruptionTypeKey] as! NSValue).getValue(&intValue)

              if let type = AVAudioSessionInterruptionType(rawValue: intValue)
              {
              switch type
              {
              case .Began:
              print("aaaaarrrrgggg you stole me")
              player.pause()
              case .Ended:
              let timer = NSTimer.scheduledTimerWithTimeInterval(3, target: self, selector: "resumeNow:", userInfo: nil, repeats: false)
              }
              }
              }
              }

              func resumeNow(timer : NSTimer)
              {
              player.play()
              print("attempted restart")
              }





              share|improve this answer























              • Tried it, but doesn't seem to do anything. Audio still doesn't play on resume.
                – Simon Newstead
                Sep 13 '15 at 9:57










              • Where did you put the code?
                – Jason Nam
                Sep 13 '15 at 9:57










              • in both: case .Ended and in resumeNow just before player.play() have you managed to get it working?
                – Simon Newstead
                Sep 13 '15 at 10:00










              • Check this answers stackoverflow.com/questions/12461691/…
                – Jason Nam
                Sep 13 '15 at 10:16










              • Hi Jason thanks but that doesn't seem to help solve the problem (and was from a long while ago - can I see where it's been fixed or documented?)
                – Simon Newstead
                Sep 14 '15 at 3:05
















              1














              I wrote a code like this and successfully resumed the audio from the phone call ended. I was build on Xcode 6.4 and ran the app on my iPhone 4S.



              var player: AVQueuePlayer! = nil

              override func viewDidLoad()
              {
              super.viewDidLoad()
              // Do any additional setup after loading the view, typically from a nib.
              }

              override func viewDidAppear(animated: Bool)
              {
              super.viewDidAppear(true)

              var song = AVPlayerItem(URL: NSBundle.mainBundle().URLForResource("AlmostAYearAgo", withExtension: "mp3")!)
              player = AVQueuePlayer(items: [song])

              let theSession = AVAudioSession.sharedInstance()

              NSNotificationCenter.defaultCenter().addObserver(self, selector: "playInterrupt:", name: AVAudioSessionInterruptionNotification, object: theSession)

              player.play()
              }

              override func didReceiveMemoryWarning()
              {
              super.didReceiveMemoryWarning()
              // Dispose of any resources that can be recreated.
              }

              func playInterrupt(notification: NSNotification)
              {
              if notification.name == AVAudioSessionInterruptionNotification && notification.userInfo != nil
              {
              var info = notification.userInfo!
              var intValue: UInt = 0

              (info[AVAudioSessionInterruptionTypeKey] as! NSValue).getValue(&intValue)

              if let type = AVAudioSessionInterruptionType(rawValue: intValue)
              {
              switch type
              {
              case .Began:
              print("aaaaarrrrgggg you stole me")
              player.pause()
              case .Ended:
              let timer = NSTimer.scheduledTimerWithTimeInterval(3, target: self, selector: "resumeNow:", userInfo: nil, repeats: false)
              }
              }
              }
              }

              func resumeNow(timer : NSTimer)
              {
              player.play()
              print("attempted restart")
              }





              share|improve this answer























              • Tried it, but doesn't seem to do anything. Audio still doesn't play on resume.
                – Simon Newstead
                Sep 13 '15 at 9:57










              • Where did you put the code?
                – Jason Nam
                Sep 13 '15 at 9:57










              • in both: case .Ended and in resumeNow just before player.play() have you managed to get it working?
                – Simon Newstead
                Sep 13 '15 at 10:00










              • Check this answers stackoverflow.com/questions/12461691/…
                – Jason Nam
                Sep 13 '15 at 10:16










              • Hi Jason thanks but that doesn't seem to help solve the problem (and was from a long while ago - can I see where it's been fixed or documented?)
                – Simon Newstead
                Sep 14 '15 at 3:05














              1












              1








              1






              I wrote a code like this and successfully resumed the audio from the phone call ended. I was build on Xcode 6.4 and ran the app on my iPhone 4S.



              var player: AVQueuePlayer! = nil

              override func viewDidLoad()
              {
              super.viewDidLoad()
              // Do any additional setup after loading the view, typically from a nib.
              }

              override func viewDidAppear(animated: Bool)
              {
              super.viewDidAppear(true)

              var song = AVPlayerItem(URL: NSBundle.mainBundle().URLForResource("AlmostAYearAgo", withExtension: "mp3")!)
              player = AVQueuePlayer(items: [song])

              let theSession = AVAudioSession.sharedInstance()

              NSNotificationCenter.defaultCenter().addObserver(self, selector: "playInterrupt:", name: AVAudioSessionInterruptionNotification, object: theSession)

              player.play()
              }

              override func didReceiveMemoryWarning()
              {
              super.didReceiveMemoryWarning()
              // Dispose of any resources that can be recreated.
              }

              func playInterrupt(notification: NSNotification)
              {
              if notification.name == AVAudioSessionInterruptionNotification && notification.userInfo != nil
              {
              var info = notification.userInfo!
              var intValue: UInt = 0

              (info[AVAudioSessionInterruptionTypeKey] as! NSValue).getValue(&intValue)

              if let type = AVAudioSessionInterruptionType(rawValue: intValue)
              {
              switch type
              {
              case .Began:
              print("aaaaarrrrgggg you stole me")
              player.pause()
              case .Ended:
              let timer = NSTimer.scheduledTimerWithTimeInterval(3, target: self, selector: "resumeNow:", userInfo: nil, repeats: false)
              }
              }
              }
              }

              func resumeNow(timer : NSTimer)
              {
              player.play()
              print("attempted restart")
              }





              share|improve this answer














              I wrote a code like this and successfully resumed the audio from the phone call ended. I was build on Xcode 6.4 and ran the app on my iPhone 4S.



              var player: AVQueuePlayer! = nil

              override func viewDidLoad()
              {
              super.viewDidLoad()
              // Do any additional setup after loading the view, typically from a nib.
              }

              override func viewDidAppear(animated: Bool)
              {
              super.viewDidAppear(true)

              var song = AVPlayerItem(URL: NSBundle.mainBundle().URLForResource("AlmostAYearAgo", withExtension: "mp3")!)
              player = AVQueuePlayer(items: [song])

              let theSession = AVAudioSession.sharedInstance()

              NSNotificationCenter.defaultCenter().addObserver(self, selector: "playInterrupt:", name: AVAudioSessionInterruptionNotification, object: theSession)

              player.play()
              }

              override func didReceiveMemoryWarning()
              {
              super.didReceiveMemoryWarning()
              // Dispose of any resources that can be recreated.
              }

              func playInterrupt(notification: NSNotification)
              {
              if notification.name == AVAudioSessionInterruptionNotification && notification.userInfo != nil
              {
              var info = notification.userInfo!
              var intValue: UInt = 0

              (info[AVAudioSessionInterruptionTypeKey] as! NSValue).getValue(&intValue)

              if let type = AVAudioSessionInterruptionType(rawValue: intValue)
              {
              switch type
              {
              case .Began:
              print("aaaaarrrrgggg you stole me")
              player.pause()
              case .Ended:
              let timer = NSTimer.scheduledTimerWithTimeInterval(3, target: self, selector: "resumeNow:", userInfo: nil, repeats: false)
              }
              }
              }
              }

              func resumeNow(timer : NSTimer)
              {
              player.play()
              print("attempted restart")
              }






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Sep 16 '15 at 10:58

























              answered Sep 13 '15 at 9:53









              Jason NamJason Nam

              1,8301922




              1,8301922












              • Tried it, but doesn't seem to do anything. Audio still doesn't play on resume.
                – Simon Newstead
                Sep 13 '15 at 9:57










              • Where did you put the code?
                – Jason Nam
                Sep 13 '15 at 9:57










              • in both: case .Ended and in resumeNow just before player.play() have you managed to get it working?
                – Simon Newstead
                Sep 13 '15 at 10:00










              • Check this answers stackoverflow.com/questions/12461691/…
                – Jason Nam
                Sep 13 '15 at 10:16










              • Hi Jason thanks but that doesn't seem to help solve the problem (and was from a long while ago - can I see where it's been fixed or documented?)
                – Simon Newstead
                Sep 14 '15 at 3:05


















              • Tried it, but doesn't seem to do anything. Audio still doesn't play on resume.
                – Simon Newstead
                Sep 13 '15 at 9:57










              • Where did you put the code?
                – Jason Nam
                Sep 13 '15 at 9:57










              • in both: case .Ended and in resumeNow just before player.play() have you managed to get it working?
                – Simon Newstead
                Sep 13 '15 at 10:00










              • Check this answers stackoverflow.com/questions/12461691/…
                – Jason Nam
                Sep 13 '15 at 10:16










              • Hi Jason thanks but that doesn't seem to help solve the problem (and was from a long while ago - can I see where it's been fixed or documented?)
                – Simon Newstead
                Sep 14 '15 at 3:05
















              Tried it, but doesn't seem to do anything. Audio still doesn't play on resume.
              – Simon Newstead
              Sep 13 '15 at 9:57




              Tried it, but doesn't seem to do anything. Audio still doesn't play on resume.
              – Simon Newstead
              Sep 13 '15 at 9:57












              Where did you put the code?
              – Jason Nam
              Sep 13 '15 at 9:57




              Where did you put the code?
              – Jason Nam
              Sep 13 '15 at 9:57












              in both: case .Ended and in resumeNow just before player.play() have you managed to get it working?
              – Simon Newstead
              Sep 13 '15 at 10:00




              in both: case .Ended and in resumeNow just before player.play() have you managed to get it working?
              – Simon Newstead
              Sep 13 '15 at 10:00












              Check this answers stackoverflow.com/questions/12461691/…
              – Jason Nam
              Sep 13 '15 at 10:16




              Check this answers stackoverflow.com/questions/12461691/…
              – Jason Nam
              Sep 13 '15 at 10:16












              Hi Jason thanks but that doesn't seem to help solve the problem (and was from a long while ago - can I see where it's been fixed or documented?)
              – Simon Newstead
              Sep 14 '15 at 3:05




              Hi Jason thanks but that doesn't seem to help solve the problem (and was from a long while ago - can I see where it's been fixed or documented?)
              – Simon Newstead
              Sep 14 '15 at 3:05











              0














              For me reload player after end interruption resolve the problem:



                  func interruptionNotification(_ notification: Notification) {
              guard let type = notification.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt,
              let interruption = AVAudioSessionInterruptionType(rawValue: type) else {
              return
              }
              if interruption == .ended && playerWasPlayingBeforeInterruption {
              player.replaceCurrentItem(with: AVPlayerItem(url: radioStation.url))
              play()
              }
              }





              share|improve this answer


























                0














                For me reload player after end interruption resolve the problem:



                    func interruptionNotification(_ notification: Notification) {
                guard let type = notification.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt,
                let interruption = AVAudioSessionInterruptionType(rawValue: type) else {
                return
                }
                if interruption == .ended && playerWasPlayingBeforeInterruption {
                player.replaceCurrentItem(with: AVPlayerItem(url: radioStation.url))
                play()
                }
                }





                share|improve this answer
























                  0












                  0








                  0






                  For me reload player after end interruption resolve the problem:



                      func interruptionNotification(_ notification: Notification) {
                  guard let type = notification.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt,
                  let interruption = AVAudioSessionInterruptionType(rawValue: type) else {
                  return
                  }
                  if interruption == .ended && playerWasPlayingBeforeInterruption {
                  player.replaceCurrentItem(with: AVPlayerItem(url: radioStation.url))
                  play()
                  }
                  }





                  share|improve this answer












                  For me reload player after end interruption resolve the problem:



                      func interruptionNotification(_ notification: Notification) {
                  guard let type = notification.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt,
                  let interruption = AVAudioSessionInterruptionType(rawValue: type) else {
                  return
                  }
                  if interruption == .ended && playerWasPlayingBeforeInterruption {
                  player.replaceCurrentItem(with: AVPlayerItem(url: radioStation.url))
                  play()
                  }
                  }






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Apr 19 '17 at 18:43









                  Vitaliy GozhenkoVitaliy Gozhenko

                  6,40923054




                  6,40923054























                      -1














                      Simon, absolutely confirm it on my end. I spend 2 days looking for it! If you use just:



                      AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) then does not matter what you do your player will not resume playing audio if you use instead:



                      AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, withOptions: AVAudioSessionCategoryOptions.MixWithOthers)



                      then it works like perfect and will resume after receiving phone call while the app is in the background.



                      Thanks!






                      share|improve this answer





















                      • Simon, not sure if you noticed but this is not the working solution. I thought the solution was working but when you use: AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, withOptions: AVAudioSessionCategoryOptions.MixWithOthers then your player will mix with others. Try staring music app as well in the same time. You will get 2 sounds playing at the same time and mixing. It works for resuming after the call while in the background but it messes up the whole playback of your sound. Anyone any idea please?
                        – aurawindsurfing
                        Sep 19 '15 at 10:05












                      • The thing that we were missing was self.becomeFirstResponder() once that was added the whole thing started to work for me.
                        – aurawindsurfing
                        Sep 19 '15 at 17:16










                      • Good to know, thanks. I don't need it because my app is a silent meditation app and they won't mix audio themselves, so hadn't tested that option.
                        – Simon Newstead
                        Sep 21 '15 at 7:37
















                      -1














                      Simon, absolutely confirm it on my end. I spend 2 days looking for it! If you use just:



                      AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) then does not matter what you do your player will not resume playing audio if you use instead:



                      AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, withOptions: AVAudioSessionCategoryOptions.MixWithOthers)



                      then it works like perfect and will resume after receiving phone call while the app is in the background.



                      Thanks!






                      share|improve this answer





















                      • Simon, not sure if you noticed but this is not the working solution. I thought the solution was working but when you use: AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, withOptions: AVAudioSessionCategoryOptions.MixWithOthers then your player will mix with others. Try staring music app as well in the same time. You will get 2 sounds playing at the same time and mixing. It works for resuming after the call while in the background but it messes up the whole playback of your sound. Anyone any idea please?
                        – aurawindsurfing
                        Sep 19 '15 at 10:05












                      • The thing that we were missing was self.becomeFirstResponder() once that was added the whole thing started to work for me.
                        – aurawindsurfing
                        Sep 19 '15 at 17:16










                      • Good to know, thanks. I don't need it because my app is a silent meditation app and they won't mix audio themselves, so hadn't tested that option.
                        – Simon Newstead
                        Sep 21 '15 at 7:37














                      -1












                      -1








                      -1






                      Simon, absolutely confirm it on my end. I spend 2 days looking for it! If you use just:



                      AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) then does not matter what you do your player will not resume playing audio if you use instead:



                      AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, withOptions: AVAudioSessionCategoryOptions.MixWithOthers)



                      then it works like perfect and will resume after receiving phone call while the app is in the background.



                      Thanks!






                      share|improve this answer












                      Simon, absolutely confirm it on my end. I spend 2 days looking for it! If you use just:



                      AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) then does not matter what you do your player will not resume playing audio if you use instead:



                      AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, withOptions: AVAudioSessionCategoryOptions.MixWithOthers)



                      then it works like perfect and will resume after receiving phone call while the app is in the background.



                      Thanks!







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Sep 18 '15 at 13:41









                      aurawindsurfingaurawindsurfing

                      10317




                      10317












                      • Simon, not sure if you noticed but this is not the working solution. I thought the solution was working but when you use: AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, withOptions: AVAudioSessionCategoryOptions.MixWithOthers then your player will mix with others. Try staring music app as well in the same time. You will get 2 sounds playing at the same time and mixing. It works for resuming after the call while in the background but it messes up the whole playback of your sound. Anyone any idea please?
                        – aurawindsurfing
                        Sep 19 '15 at 10:05












                      • The thing that we were missing was self.becomeFirstResponder() once that was added the whole thing started to work for me.
                        – aurawindsurfing
                        Sep 19 '15 at 17:16










                      • Good to know, thanks. I don't need it because my app is a silent meditation app and they won't mix audio themselves, so hadn't tested that option.
                        – Simon Newstead
                        Sep 21 '15 at 7:37


















                      • Simon, not sure if you noticed but this is not the working solution. I thought the solution was working but when you use: AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, withOptions: AVAudioSessionCategoryOptions.MixWithOthers then your player will mix with others. Try staring music app as well in the same time. You will get 2 sounds playing at the same time and mixing. It works for resuming after the call while in the background but it messes up the whole playback of your sound. Anyone any idea please?
                        – aurawindsurfing
                        Sep 19 '15 at 10:05












                      • The thing that we were missing was self.becomeFirstResponder() once that was added the whole thing started to work for me.
                        – aurawindsurfing
                        Sep 19 '15 at 17:16










                      • Good to know, thanks. I don't need it because my app is a silent meditation app and they won't mix audio themselves, so hadn't tested that option.
                        – Simon Newstead
                        Sep 21 '15 at 7:37
















                      Simon, not sure if you noticed but this is not the working solution. I thought the solution was working but when you use: AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, withOptions: AVAudioSessionCategoryOptions.MixWithOthers then your player will mix with others. Try staring music app as well in the same time. You will get 2 sounds playing at the same time and mixing. It works for resuming after the call while in the background but it messes up the whole playback of your sound. Anyone any idea please?
                      – aurawindsurfing
                      Sep 19 '15 at 10:05






                      Simon, not sure if you noticed but this is not the working solution. I thought the solution was working but when you use: AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, withOptions: AVAudioSessionCategoryOptions.MixWithOthers then your player will mix with others. Try staring music app as well in the same time. You will get 2 sounds playing at the same time and mixing. It works for resuming after the call while in the background but it messes up the whole playback of your sound. Anyone any idea please?
                      – aurawindsurfing
                      Sep 19 '15 at 10:05














                      The thing that we were missing was self.becomeFirstResponder() once that was added the whole thing started to work for me.
                      – aurawindsurfing
                      Sep 19 '15 at 17:16




                      The thing that we were missing was self.becomeFirstResponder() once that was added the whole thing started to work for me.
                      – aurawindsurfing
                      Sep 19 '15 at 17:16












                      Good to know, thanks. I don't need it because my app is a silent meditation app and they won't mix audio themselves, so hadn't tested that option.
                      – Simon Newstead
                      Sep 21 '15 at 7:37




                      Good to know, thanks. I don't need it because my app is a silent meditation app and they won't mix audio themselves, so hadn't tested that option.
                      – Simon Newstead
                      Sep 21 '15 at 7:37


















                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f32548236%2fhow-to-resume-background-audio-in-swift-2-avplayer%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Feedback on college project

                      Futebolista

                      Albești (Vaslui)