BackgroundTaskAudio.swift 2.1 KB

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