NCAudioRecorderViewController.swift 8.9 KB

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