NCAudioRecorderViewController.swift 8.9 KB

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