BackgroundTaskAudio.swift 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. //
  2. // BackgroundTask.swift
  3. //
  4. // Created by Yaro on 8/27/16.
  5. // Copyright © 2016 Yaro. All rights reserved.
  6. //
  7. import AVFoundation
  8. class BackgroundTask {
  9. // MARK: - Vars
  10. var player = AVAudioPlayer()
  11. var timer = Timer()
  12. // MARK: - Methods
  13. func startBackgroundTask() {
  14. NotificationCenter.default.addObserver(self, selector: #selector(interruptedAudio), name: AVAudioSession.interruptionNotification, object: AVAudioSession.sharedInstance())
  15. self.playAudio()
  16. }
  17. func stopBackgroundTask() {
  18. NotificationCenter.default.removeObserver(self, name: AVAudioSession.interruptionNotification, object: nil)
  19. player.stop()
  20. }
  21. @objc fileprivate func interruptedAudio(_ notification: Notification) {
  22. if notification.name == AVAudioSession.interruptionNotification && notification.userInfo != nil {
  23. var info = notification.userInfo!
  24. var intValue = 0
  25. (info[AVAudioSessionInterruptionTypeKey]! as AnyObject).getValue(&intValue)
  26. if intValue == 1 { playAudio() }
  27. }
  28. }
  29. fileprivate func playAudio() {
  30. do {
  31. let bundle = Bundle.main.path(forResource: "blank", ofType: "wav")
  32. let alertSound = URL(fileURLWithPath: bundle!)
  33. // try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)
  34. try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: .mixWithOthers)
  35. try AVAudioSession.sharedInstance().setActive(true)
  36. try self.player = AVAudioPlayer(contentsOf: alertSound)
  37. // Play audio forever by setting num of loops to -1
  38. self.player.numberOfLoops = -1
  39. self.player.volume = 0.01
  40. self.player.prepareToPlay()
  41. self.player.play()
  42. print("silent audio playing")
  43. } catch { print(error)
  44. }
  45. }
  46. }