NCAudioRecorderViewController.swift 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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 startDate: Date = Date()
  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. view.backgroundColor = .clear
  49. contentContainerView.backgroundColor = UIColor.lightGray
  50. voiceRecordHUD.fillColor = UIColor.green
  51. }
  52. override func viewWillAppear(_ animated: Bool) {
  53. super.viewWillAppear(animated)
  54. }
  55. override func viewDidAppear(_ animated: Bool) {
  56. super.viewDidAppear(animated)
  57. }
  58. override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
  59. super.traitCollectionDidChange(previousTraitCollection)
  60. }
  61. // MARK: - Action
  62. @IBAction func touchViewController() {
  63. if recording.state == .record {
  64. startStop()
  65. } else {
  66. dismiss(animated: true) {
  67. self.delegate?.didFinishWithoutRecording(self, fileName: self.fileName)
  68. }
  69. }
  70. }
  71. @IBAction func startStop() {
  72. if recording.state == .record {
  73. recording.stop()
  74. voiceRecordHUD.update(0.0)
  75. dismiss(animated: true) {
  76. self.delegate?.didFinishRecording(self, fileName: self.fileName)
  77. }
  78. } else {
  79. do {
  80. try recording.record()
  81. startDate = Date()
  82. startStopLabel.text = NSLocalizedString("_voice_memo_stop_", comment: "")
  83. } catch {
  84. print(error)
  85. }
  86. }
  87. }
  88. // MARK: - Code
  89. func createRecorder(fileName: String) {
  90. self.fileName = fileName
  91. recording = NCAudioRecorder(to: fileName)
  92. recording.delegate = self
  93. DispatchQueue.global().async {
  94. // Background thread
  95. do {
  96. try self.recording.prepare()
  97. } catch {
  98. print(error)
  99. }
  100. }
  101. }
  102. func audioMeterDidUpdate(_ db: Float) {
  103. // print("db level: %f", db)
  104. self.recording.recorder?.updateMeters()
  105. let ALPHA = 0.05
  106. let peakPower = pow(10, (ALPHA * Double((self.recording.recorder?.peakPower(forChannel: 0))!)))
  107. var rate: Double = 0.0
  108. if peakPower <= 0.2 {
  109. rate = 0.2
  110. } else if peakPower > 0.9 {
  111. rate = 1.0
  112. } else {
  113. rate = peakPower
  114. }
  115. voiceRecordHUD.update(CGFloat(rate))
  116. voiceRecordHUD.fillColor = UIColor.green
  117. let formatter = DateComponentsFormatter()
  118. formatter.allowedUnits = [.second]
  119. formatter.unitsStyle = .full
  120. durationLabel.text = formatter.string(from: startDate, to: Date())
  121. }
  122. }
  123. @objc public protocol NCAudioRecorderDelegate: AVAudioRecorderDelegate {
  124. @objc optional func audioMeterDidUpdate(_ dB: Float)
  125. }
  126. open class NCAudioRecorder: NSObject {
  127. @objc public enum State: Int {
  128. case none, record, play
  129. }
  130. static var directory: String {
  131. return NSTemporaryDirectory()
  132. }
  133. open weak var delegate: NCAudioRecorderDelegate?
  134. open fileprivate(set) var url: URL
  135. open fileprivate(set) var state: State = .none
  136. open var bitRate = 192000
  137. open var sampleRate = 44100.0
  138. open var channels = 1
  139. var recorder: AVAudioRecorder?
  140. fileprivate var player: AVAudioPlayer?
  141. fileprivate var link: CADisplayLink?
  142. var metering: Bool {
  143. return delegate?.responds(to: #selector(NCAudioRecorderDelegate.audioMeterDidUpdate(_:))) == true
  144. }
  145. // MARK: - Initializers
  146. public init(to fileName: String) {
  147. url = URL(fileURLWithPath: NCAudioRecorder.directory).appendingPathComponent(fileName)
  148. super.init()
  149. do {
  150. try AVAudioSession.sharedInstance().setCategory(.playAndRecord)
  151. try AVAudioSession.sharedInstance().overrideOutputAudioPort(AVAudioSession.PortOverride.speaker)
  152. try AVAudioSession.sharedInstance().setActive(true)
  153. } catch {
  154. print(error)
  155. }
  156. }
  157. deinit {
  158. print("deinit NCAudioRecorder")
  159. do {
  160. try AVAudioSession.sharedInstance().setActive(false)
  161. } catch {
  162. print(error)
  163. }
  164. }
  165. // MARK: - Record
  166. open func prepare() throws {
  167. let settings: [String: AnyObject] = [
  168. AVFormatIDKey: NSNumber(value: Int32(kAudioFormatAppleLossless) as Int32),
  169. AVEncoderAudioQualityKey: AVAudioQuality.max.rawValue as AnyObject,
  170. AVEncoderBitRateKey: bitRate as AnyObject,
  171. AVNumberOfChannelsKey: channels as AnyObject,
  172. AVSampleRateKey: sampleRate as AnyObject
  173. ]
  174. recorder = try AVAudioRecorder(url: url, settings: settings)
  175. recorder?.prepareToRecord()
  176. recorder?.delegate = delegate
  177. recorder?.isMeteringEnabled = metering
  178. }
  179. open func record() throws {
  180. if recorder == nil {
  181. try prepare()
  182. }
  183. self.state = .record
  184. if self.metering {
  185. self.startMetering()
  186. }
  187. self.recorder?.record()
  188. }
  189. open func stop() {
  190. switch state {
  191. case .play:
  192. player?.stop()
  193. player = nil
  194. case .record:
  195. recorder?.stop()
  196. recorder = nil
  197. stopMetering()
  198. default:
  199. break
  200. }
  201. state = .none
  202. }
  203. // MARK: - Metering
  204. @objc func updateMeter() {
  205. guard let recorder = recorder else { return }
  206. recorder.updateMeters()
  207. let dB = recorder.averagePower(forChannel: 0)
  208. delegate?.audioMeterDidUpdate?(dB)
  209. }
  210. fileprivate func startMetering() {
  211. link = CADisplayLink(target: self, selector: #selector(NCAudioRecorder.updateMeter))
  212. link?.add(to: RunLoop.current, forMode: RunLoop.Mode.common)
  213. }
  214. fileprivate func stopMetering() {
  215. link?.invalidate()
  216. link = nil
  217. }
  218. }
  219. @IBDesignable
  220. class VoiceRecordHUD: UIView {
  221. @IBInspectable var rate: CGFloat = 0.0
  222. @IBInspectable var fillColor: UIColor = UIColor.green {
  223. didSet {
  224. setNeedsDisplay()
  225. }
  226. }
  227. var image: UIImage! {
  228. didSet {
  229. setNeedsDisplay()
  230. }
  231. }
  232. // MARK: - View Life Cycle
  233. override init(frame: CGRect) {
  234. super.init(frame: frame)
  235. image = UIImage(named: "microphone")
  236. }
  237. required init?(coder aDecoder: NSCoder) {
  238. super.init(coder: aDecoder)
  239. image = UIImage(named: "microphone")
  240. }
  241. func update(_ rate: CGFloat) {
  242. self.rate = rate
  243. setNeedsDisplay()
  244. }
  245. override func draw(_ rect: CGRect) {
  246. let context = UIGraphicsGetCurrentContext()
  247. context?.translateBy(x: 0, y: bounds.size.height)
  248. context?.scaleBy(x: 1, y: -1)
  249. context?.draw(image.cgImage!, in: bounds)
  250. context?.clip(to: bounds, mask: image.cgImage!)
  251. context?.setFillColor(fillColor.cgColor.components!)
  252. context?.fill(CGRect(x: 0, y: 0, width: bounds.width, height: bounds.height * rate))
  253. }
  254. override func prepareForInterfaceBuilder() {
  255. let bundle = Bundle(for: type(of: self))
  256. image = UIImage(named: "microphone", in: bundle, compatibleWith: self.traitCollection)
  257. }
  258. }