NCAudioRecorderViewController.swift 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. //
  2. // NCAudioRecorderViewController.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 08/03/19.
  6. // Copyright (c) 2019 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. // --------------------------------
  24. // Based on code of Venkat Kukunuru
  25. // --------------------------------
  26. import UIKit
  27. import AVFoundation
  28. import QuartzCore
  29. @objc protocol NCAudioRecorderViewControllerDelegate: AnyObject {
  30. func didFinishRecording(_ viewController: NCAudioRecorderViewController, fileName: String)
  31. func didFinishWithoutRecording(_ viewController: NCAudioRecorderViewController, fileName: String)
  32. }
  33. class NCAudioRecorderViewController: UIViewController, NCAudioRecorderDelegate {
  34. open weak var delegate: NCAudioRecorderViewControllerDelegate?
  35. var recording: NCAudioRecorder!
  36. var recordDuration: TimeInterval = 0
  37. var fileName: String = ""
  38. @IBOutlet weak var contentContainerView: UIView!
  39. @IBOutlet weak var durationLabel: UILabel!
  40. @IBOutlet weak var startStopLabel: UILabel!
  41. @IBOutlet weak var voiceRecordHUD: VoiceRecordHUD!
  42. // MARK: - View Life Cycle
  43. override func viewDidLoad() {
  44. super.viewDidLoad()
  45. voiceRecordHUD.update(0.0)
  46. durationLabel.text = ""
  47. startStopLabel.text = NSLocalizedString("_voice_memo_start_", comment: "")
  48. changeTheming()
  49. }
  50. override func viewWillAppear(_ animated: Bool) {
  51. super.viewWillAppear(animated)
  52. }
  53. override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
  54. super.traitCollectionDidChange(previousTraitCollection)
  55. changeTheming()
  56. }
  57. // MARK: - Colors
  58. func changeTheming() {
  59. view.backgroundColor = .clear
  60. contentContainerView.backgroundColor = UIColor.lightGray
  61. voiceRecordHUD.fillColor = UIColor.green
  62. }
  63. // MARK: - Action
  64. @IBAction func touchViewController() {
  65. if recording.state == .record {
  66. startStop()
  67. } else {
  68. dismiss(animated: true) {
  69. self.delegate?.didFinishWithoutRecording(self, fileName: self.fileName)
  70. }
  71. }
  72. }
  73. @IBAction func startStop() {
  74. if recording.state == .record {
  75. recordDuration = 0
  76. recording.stop()
  77. voiceRecordHUD.update(0.0)
  78. dismiss(animated: true) {
  79. self.delegate?.didFinishRecording(self, fileName: self.fileName)
  80. }
  81. } else {
  82. recordDuration = 0
  83. do {
  84. try recording.record()
  85. startStopLabel.text = NSLocalizedString("_voice_memo_stop_", comment: "")
  86. } catch {
  87. print(error)
  88. }
  89. }
  90. }
  91. // MARK: - Code
  92. func createRecorder(fileName: String) {
  93. self.fileName = fileName
  94. recording = NCAudioRecorder(to: fileName)
  95. recording.delegate = self
  96. DispatchQueue.global().async {
  97. // Background thread
  98. do {
  99. try self.recording.prepare()
  100. } catch {
  101. print(error)
  102. }
  103. }
  104. }
  105. func audioMeterDidUpdate(_ db: Float) {
  106. // print("db level: %f", db)
  107. self.recording.recorder?.updateMeters()
  108. let ALPHA = 0.05
  109. let peakPower = pow(10, (ALPHA * Double((self.recording.recorder?.peakPower(forChannel: 0))!)))
  110. var rate: Double = 0.0
  111. if peakPower <= 0.2 {
  112. rate = 0.2
  113. } else if peakPower > 0.9 {
  114. rate = 1.0
  115. } else {
  116. rate = peakPower
  117. }
  118. voiceRecordHUD.update(CGFloat(rate))
  119. voiceRecordHUD.fillColor = UIColor.green
  120. recordDuration += 1
  121. durationLabel.text = String().formatSecondsToString(recordDuration/60)
  122. }
  123. }
  124. @objc public protocol NCAudioRecorderDelegate: AVAudioRecorderDelegate {
  125. @objc optional func audioMeterDidUpdate(_ dB: Float)
  126. }
  127. open class NCAudioRecorder: NSObject {
  128. @objc public enum State: Int {
  129. case none, record, play
  130. }
  131. static var directory: String {
  132. return NSTemporaryDirectory()
  133. }
  134. open weak var delegate: NCAudioRecorderDelegate?
  135. open fileprivate(set) var url: URL
  136. open fileprivate(set) var state: State = .none
  137. open var bitRate = 192000
  138. open var sampleRate = 44100.0
  139. open var channels = 1
  140. var recorder: AVAudioRecorder?
  141. fileprivate var player: AVAudioPlayer?
  142. fileprivate var link: CADisplayLink?
  143. var metering: Bool {
  144. return delegate?.responds(to: #selector(NCAudioRecorderDelegate.audioMeterDidUpdate(_:))) == true
  145. }
  146. // MARK: - Initializers
  147. public init(to: String) {
  148. url = URL(fileURLWithPath: NCAudioRecorder.directory).appendingPathComponent(to)
  149. super.init()
  150. do {
  151. try AVAudioSession.sharedInstance().setCategory(.playAndRecord)
  152. try AVAudioSession.sharedInstance().overrideOutputAudioPort(AVAudioSession.PortOverride.speaker)
  153. try AVAudioSession.sharedInstance().setActive(true)
  154. } catch {
  155. print(error)
  156. }
  157. }
  158. deinit {
  159. print("deinit NCAudioRecorder")
  160. do {
  161. try AVAudioSession.sharedInstance().setActive(false)
  162. } catch {
  163. print(error)
  164. }
  165. }
  166. // MARK: - Record
  167. open func prepare() throws {
  168. let settings: [String: AnyObject] = [
  169. AVFormatIDKey: NSNumber(value: Int32(kAudioFormatAppleLossless) as Int32),
  170. AVEncoderAudioQualityKey: AVAudioQuality.max.rawValue as AnyObject,
  171. AVEncoderBitRateKey: bitRate as AnyObject,
  172. AVNumberOfChannelsKey: channels as AnyObject,
  173. AVSampleRateKey: sampleRate as AnyObject
  174. ]
  175. recorder = try AVAudioRecorder(url: url, settings: settings)
  176. recorder?.prepareToRecord()
  177. recorder?.delegate = delegate
  178. recorder?.isMeteringEnabled = metering
  179. }
  180. open func record() throws {
  181. if recorder == nil {
  182. try prepare()
  183. }
  184. self.state = .record
  185. if self.metering {
  186. self.startMetering()
  187. }
  188. self.recorder?.record()
  189. }
  190. open func stop() {
  191. switch state {
  192. case .play:
  193. player?.stop()
  194. player = nil
  195. case .record:
  196. recorder?.stop()
  197. recorder = nil
  198. stopMetering()
  199. default:
  200. break
  201. }
  202. state = .none
  203. }
  204. // MARK: - Metering
  205. @objc func updateMeter() {
  206. guard let recorder = recorder else { return }
  207. recorder.updateMeters()
  208. let dB = recorder.averagePower(forChannel: 0)
  209. delegate?.audioMeterDidUpdate?(dB)
  210. }
  211. fileprivate func startMetering() {
  212. link = CADisplayLink(target: self, selector: #selector(NCAudioRecorder.updateMeter))
  213. link?.add(to: RunLoop.current, forMode: RunLoop.Mode.common)
  214. }
  215. fileprivate func stopMetering() {
  216. link?.invalidate()
  217. link = nil
  218. }
  219. }
  220. @IBDesignable
  221. class VoiceRecordHUD: UIView {
  222. @IBInspectable var rate: CGFloat = 0.0
  223. @IBInspectable var fillColor: UIColor = UIColor.green {
  224. didSet {
  225. setNeedsDisplay()
  226. }
  227. }
  228. var image: UIImage! {
  229. didSet {
  230. setNeedsDisplay()
  231. }
  232. }
  233. // MARK: - View Life Cycle
  234. override init(frame: CGRect) {
  235. super.init(frame: frame)
  236. image = UIImage(named: "microphone")
  237. }
  238. required init?(coder aDecoder: NSCoder) {
  239. super.init(coder: aDecoder)
  240. image = UIImage(named: "microphone")
  241. }
  242. func update(_ rate: CGFloat) {
  243. self.rate = rate
  244. setNeedsDisplay()
  245. }
  246. override func draw(_ rect: CGRect) {
  247. let context = UIGraphicsGetCurrentContext()
  248. context?.translateBy(x: 0, y: bounds.size.height)
  249. context?.scaleBy(x: 1, y: -1)
  250. context?.draw(image.cgImage!, in: bounds)
  251. context?.clip(to: bounds, mask: image.cgImage!)
  252. context?.setFillColor(fillColor.cgColor.components!)
  253. context?.fill(CGRect(x: 0, y: 0, width: bounds.width, height: bounds.height * rate))
  254. }
  255. override func prepareForInterfaceBuilder() {
  256. let bundle = Bundle(for: type(of: self))
  257. image = UIImage(named: "microphone", in: bundle, compatibleWith: self.traitCollection)
  258. }
  259. }