AudioController.swift 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. import UIKit
  2. import AVFoundation
  3. import DcCore
  4. /// The `PlayerState` indicates the current audio controller state
  5. public enum PlayerState {
  6. /// The audio controller is currently playing a sound
  7. case playing
  8. /// The audio controller is currently in pause state
  9. case pause
  10. /// The audio controller is not playing any sound and audioPlayer is nil
  11. case stopped
  12. }
  13. public protocol AudioControllerDelegate: AnyObject {
  14. func onAudioPlayFailed()
  15. }
  16. /// The `AudioController` update UI for current audio cell that is playing a sound
  17. /// and also creates and manage an `AVAudioPlayer` states, play, pause and stop.
  18. open class AudioController: NSObject, AVAudioPlayerDelegate, AudioMessageCellDelegate {
  19. open weak var delegate: AudioControllerDelegate?
  20. lazy var audioSession: AVAudioSession = {
  21. let audioSession = AVAudioSession.sharedInstance()
  22. _ = try? audioSession.setCategory(AVAudioSession.Category.playback, options: [.defaultToSpeaker])
  23. return audioSession
  24. }()
  25. /// The `AVAudioPlayer` that is playing the sound
  26. open var audioPlayer: AVAudioPlayer?
  27. /// The `AudioMessageCell` that is currently playing sound
  28. open weak var playingCell: AudioMessageCell?
  29. /// The `MessageType` that is currently playing sound
  30. open var playingMessage: DcMsg?
  31. /// Specify if current audio controller state: playing, in pause or none
  32. open private(set) var state: PlayerState = .stopped
  33. private let dcContext: DcContext
  34. private let chatId: Int
  35. private let chat: DcChat
  36. /// The `Timer` that update playing progress
  37. internal var progressTimer: Timer?
  38. // MARK: - Init Methods
  39. public init(dcContext: DcContext, chatId: Int, delegate: AudioControllerDelegate? = nil) {
  40. self.dcContext = dcContext
  41. self.chatId = chatId
  42. self.chat = dcContext.getChat(chatId: chatId)
  43. self.delegate = delegate
  44. super.init()
  45. NotificationCenter.default.addObserver(self,
  46. selector: #selector(audioRouteChanged),
  47. name: AVAudioSession.routeChangeNotification,
  48. object: AVAudioSession.sharedInstance())
  49. }
  50. deinit {
  51. NotificationCenter.default.removeObserver(self)
  52. }
  53. // MARK: - Methods
  54. /// - Parameters:
  55. /// - cell: The `NewAudioMessageCell` that needs to be configure.
  56. /// - message: The `DcMsg` that configures the cell.
  57. ///
  58. /// - Note:
  59. /// This protocol method is called by MessageKit every time an audio cell needs to be configure
  60. func update(_ cell: AudioMessageCell, with messageId: Int) {
  61. cell.delegate = self
  62. if playingMessage?.id == messageId, let player = audioPlayer {
  63. playingCell = cell
  64. cell.audioPlayerView.setProgress((player.duration == 0) ? 0 : Float(player.currentTime/player.duration))
  65. cell.audioPlayerView.showPlayLayout((player.isPlaying == true) ? true : false)
  66. cell.audioPlayerView.setDuration(duration: player.currentTime)
  67. }
  68. }
  69. public func getAudioDuration(messageId: Int, successHandler: @escaping (Int, Double) -> Void) {
  70. let message = dcContext.getMessage(id: messageId)
  71. if playingMessage?.id == messageId {
  72. // irgnore messages that are currently playing or recently paused
  73. return
  74. }
  75. DispatchQueue.global(qos: .userInitiated).async {
  76. let duration = message.duration
  77. if duration > 0 {
  78. DispatchQueue.main.async {
  79. successHandler(messageId, Double(duration) / 1000)
  80. }
  81. } else if let fileURL = message.fileURL {
  82. let audioAsset = AVURLAsset.init(url: fileURL, options: nil)
  83. audioAsset.loadValuesAsynchronously(forKeys: ["duration"]) {
  84. var error: NSError?
  85. let status = audioAsset.statusOfValue(forKey: "duration", error: &error)
  86. switch status {
  87. case .loaded:
  88. let duration = audioAsset.duration
  89. let durationInSeconds = CMTimeGetSeconds(duration)
  90. message.setLateFilingMediaSize(width: 0, height: 0, duration: Int(1000 * durationInSeconds))
  91. DispatchQueue.main.async {
  92. successHandler(messageId, Double(durationInSeconds))
  93. }
  94. case .failed:
  95. logger.warning("loading audio message \(messageId) failed: \(String(describing: error?.localizedDescription))")
  96. default: break
  97. }
  98. }
  99. }
  100. }
  101. }
  102. public func playButtonTapped(cell: AudioMessageCell, messageId: Int) {
  103. let message = dcContext.getMessage(id: messageId)
  104. guard state != .stopped else {
  105. // There is no audio sound playing - prepare to start playing for given audio message
  106. playSound(for: message, in: cell)
  107. return
  108. }
  109. if playingMessage?.messageId == message.messageId {
  110. // tap occur in the current cell that is playing audio sound
  111. if state == .playing {
  112. pauseSound(in: cell)
  113. } else {
  114. resumeSound()
  115. }
  116. } else {
  117. // tap occur in a difference cell that the one is currently playing sound. First stop currently playing and start the sound for given message
  118. stopAnyOngoingPlaying()
  119. playSound(for: message, in: cell)
  120. }
  121. }
  122. /// Used to start play audio sound
  123. ///
  124. /// - Parameters:
  125. /// - message: The `DcMsg` that contain the audio item to be played.
  126. /// - audioCell: The `NewAudioMessageCell` that needs to be updated while audio is playing.
  127. open func playSound(for message: DcMsg, in audioCell: AudioMessageCell) {
  128. if message.type == DC_MSG_AUDIO || message.type == DC_MSG_VOICE {
  129. _ = try? audioSession.setActive(true)
  130. playingCell = audioCell
  131. playingMessage = message
  132. if let fileUrl = message.fileURL, let player = try? AVAudioPlayer(contentsOf: fileUrl) {
  133. audioPlayer = player
  134. audioPlayer?.prepareToPlay()
  135. audioPlayer?.delegate = self
  136. audioPlayer?.play()
  137. state = .playing
  138. audioCell.audioPlayerView.showPlayLayout(true) // show pause button on audio cell
  139. startProgressTimer()
  140. } else {
  141. delegate?.onAudioPlayFailed()
  142. }
  143. }
  144. }
  145. /// Used to pause the audio sound
  146. ///
  147. /// - Parameters:
  148. /// - message: The `MessageType` that contain the audio item to be pause.
  149. /// - audioCell: The `AudioMessageCell` that needs to be updated by the pause action.
  150. open func pauseSound(in audioCell: AudioMessageCell) {
  151. audioPlayer?.pause()
  152. state = .pause
  153. audioCell.audioPlayerView.showPlayLayout(false) // show play button on audio cell
  154. progressTimer?.invalidate()
  155. }
  156. /// Stops any ongoing audio playing if exists
  157. open func stopAnyOngoingPlaying() {
  158. // If the audio player is nil then we don't need to go through the stopping logic
  159. guard let player = audioPlayer else { return }
  160. player.stop()
  161. state = .stopped
  162. if let cell = playingCell {
  163. cell.audioPlayerView.setProgress(0.0)
  164. cell.audioPlayerView.showPlayLayout(false)
  165. cell.audioPlayerView.setDuration(duration: player.duration)
  166. }
  167. progressTimer?.invalidate()
  168. progressTimer = nil
  169. audioPlayer = nil
  170. playingMessage = nil
  171. playingCell = nil
  172. try? audioSession.setActive(false)
  173. }
  174. /// Resume a currently pause audio sound
  175. open func resumeSound() {
  176. guard let player = audioPlayer, let cell = playingCell else {
  177. stopAnyOngoingPlaying()
  178. return
  179. }
  180. player.prepareToPlay()
  181. player.play()
  182. state = .playing
  183. startProgressTimer()
  184. cell.audioPlayerView.showPlayLayout(true) // show pause button on audio cell
  185. }
  186. // MARK: - Fire Methods
  187. @objc private func didFireProgressTimer(_ timer: Timer) {
  188. guard let player = audioPlayer, let cell = playingCell else {
  189. return
  190. }
  191. cell.audioPlayerView.setProgress((player.duration == 0) ? 0 : Float(player.currentTime/player.duration))
  192. cell.audioPlayerView.setDuration(duration: player.currentTime)
  193. }
  194. // MARK: - Private Methods
  195. private func startProgressTimer() {
  196. progressTimer?.invalidate()
  197. progressTimer = nil
  198. progressTimer = Timer.scheduledTimer(timeInterval: 0.1,
  199. target: self,
  200. selector: #selector(AudioController.didFireProgressTimer(_:)),
  201. userInfo: nil,
  202. repeats: true)
  203. }
  204. // MARK: - AVAudioPlayerDelegate
  205. open func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
  206. stopAnyOngoingPlaying()
  207. }
  208. open func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer, error: Error?) {
  209. stopAnyOngoingPlaying()
  210. }
  211. // MARK: - AVAudioSession.routeChangeNotification handler
  212. @objc func audioRouteChanged(note: Notification) {
  213. if let userInfo = note.userInfo {
  214. if let reason = userInfo[AVAudioSessionRouteChangeReasonKey] as? Int {
  215. if reason == AVAudioSession.RouteChangeReason.oldDeviceUnavailable.rawValue {
  216. // headphones plugged out
  217. resumeSound()
  218. }
  219. }
  220. }
  221. }
  222. }