NCAudioRecorderViewController.swift 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. //
  2. // NCAudioRecorderViewController.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 08/03/19.
  6. // Copyright (c) 2017 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 Foundation
  27. import UIKit
  28. import AVFoundation
  29. import QuartzCore
  30. @objc protocol NCAudioRecorderViewControllerDelegate : class {
  31. func didFinishRecording(_ viewController: NCAudioRecorderViewController)
  32. }
  33. class NCAudioRecorderViewController: UIViewController , NCAudioRecorderDelegate {
  34. open weak var delegate: NCAudioRecorderViewControllerDelegate?
  35. var recording: NCAudioRecorder!
  36. var recordDuration = 0
  37. @IBOutlet weak var contentContainerView: UIView!
  38. @IBOutlet weak var durationLabel: UILabel!
  39. @IBOutlet weak var startStopLabel: UILabel!
  40. @IBOutlet weak var voiceRecordHUD: VoiceRecordHUD!
  41. // MARK: View Life Cycle
  42. override func viewDidLoad() {
  43. super.viewDidLoad()
  44. }
  45. override func viewWillAppear(_ animated: Bool) {
  46. super.viewWillAppear(animated)
  47. contentContainerView.backgroundColor = NCBrandColor.sharedInstance.brand
  48. voiceRecordHUD.update(0.0)
  49. voiceRecordHUD.fillColor = UIColor.green
  50. durationLabel.text = ""
  51. startStopLabel.text = NSLocalizedString("_voice_memo_start_", comment: "")
  52. }
  53. func createRecorder(fileName: String) {
  54. recording = NCAudioRecorder(to: fileName)
  55. recording.delegate = self
  56. // Optionally, you can prepare the recording in the background to
  57. // make it start recording faster when you hit `record()`.
  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 startStop() {
  68. if recording.state == .none {
  69. recordDuration = 0
  70. do {
  71. try recording.record()
  72. startStopLabel.text = NSLocalizedString("_voice_memo_stop_", comment: "")
  73. } catch {
  74. print(error)
  75. }
  76. } else {
  77. delegate?.didFinishRecording(self)
  78. dismiss(animated: true, completion: nil)
  79. recordDuration = 0
  80. recording.stop()
  81. voiceRecordHUD.update(0.0)
  82. startStopLabel.text = NSLocalizedString("_voice_memo_start_", comment: "")
  83. }
  84. }
  85. func audioMeterDidUpdate(_ db: Float) {
  86. print("db level: %f", db)
  87. self.recording.recorder?.updateMeters()
  88. let ALPHA = 0.05
  89. let peakPower = pow(10, (ALPHA * Double((self.recording.recorder?.peakPower(forChannel: 0))!)))
  90. var rate: Double = 0.0
  91. if (peakPower <= 0.2) {
  92. rate = 0.2
  93. } else if (peakPower > 0.9) {
  94. rate = 1.0
  95. } else {
  96. rate = peakPower
  97. }
  98. voiceRecordHUD.update(CGFloat(rate))
  99. voiceRecordHUD.fillColor = UIColor.green
  100. recordDuration += 1
  101. durationLabel.text = String(recordDuration)
  102. }
  103. }
  104. @objc public protocol NCAudioRecorderDelegate: AVAudioRecorderDelegate {
  105. @objc optional func audioMeterDidUpdate(_ dB: Float)
  106. }
  107. open class NCAudioRecorder : NSObject {
  108. @objc public enum State: Int {
  109. case none, record, play
  110. }
  111. static var directory: String {
  112. return NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
  113. }
  114. open weak var delegate: NCAudioRecorderDelegate?
  115. open fileprivate(set) var url: URL
  116. open fileprivate(set) var state: State = .none
  117. open var bitRate = 192000
  118. open var sampleRate = 44100.0
  119. open var channels = 1
  120. fileprivate let session = AVAudioSession.sharedInstance()
  121. var recorder: AVAudioRecorder?
  122. fileprivate var player: AVAudioPlayer?
  123. fileprivate var link: CADisplayLink?
  124. var metering: Bool {
  125. return delegate?.responds(to: #selector(NCAudioRecorderDelegate.audioMeterDidUpdate(_:))) == true
  126. }
  127. // MARK: - Initializers
  128. public init(to: String) {
  129. url = URL(fileURLWithPath: NCAudioRecorder.directory).appendingPathComponent(to)
  130. super.init()
  131. }
  132. // MARK: - Record
  133. open func prepare() throws {
  134. let settings: [String: AnyObject] = [
  135. AVFormatIDKey : NSNumber(value: Int32(kAudioFormatAppleLossless) as Int32),
  136. AVEncoderAudioQualityKey: AVAudioQuality.max.rawValue as AnyObject,
  137. AVEncoderBitRateKey: bitRate as AnyObject,
  138. AVNumberOfChannelsKey: channels as AnyObject,
  139. AVSampleRateKey: sampleRate as AnyObject
  140. ]
  141. recorder = try AVAudioRecorder(url: url, settings: settings)
  142. recorder?.prepareToRecord()
  143. recorder?.delegate = delegate
  144. recorder?.isMeteringEnabled = metering
  145. }
  146. open func record() throws {
  147. if recorder == nil {
  148. try prepare()
  149. }
  150. try session.setCategory(.playAndRecord, mode: .default)
  151. try session.overrideOutputAudioPort(AVAudioSession.PortOverride.speaker)
  152. recorder?.record()
  153. state = .record
  154. if metering {
  155. startMetering()
  156. }
  157. }
  158. // MARK: - Playback
  159. open func play() throws {
  160. try session.setCategory(.playback, mode: .default)
  161. player = try AVAudioPlayer(contentsOf: url)
  162. player?.play()
  163. state = .play
  164. }
  165. open func stop() {
  166. switch state {
  167. case .play:
  168. player?.stop()
  169. player = nil
  170. case .record:
  171. recorder?.stop()
  172. recorder = nil
  173. stopMetering()
  174. default:
  175. break
  176. }
  177. state = .none
  178. }
  179. // MARK: - Metering
  180. @objc func updateMeter() {
  181. guard let recorder = recorder else { return }
  182. recorder.updateMeters()
  183. let dB = recorder.averagePower(forChannel: 0)
  184. delegate?.audioMeterDidUpdate?(dB)
  185. }
  186. fileprivate func startMetering() {
  187. link = CADisplayLink(target: self, selector: #selector(NCAudioRecorder.updateMeter))
  188. link?.add(to: RunLoop.current, forMode: RunLoop.Mode.common)
  189. }
  190. fileprivate func stopMetering() {
  191. link?.invalidate()
  192. link = nil
  193. }
  194. }
  195. @IBDesignable
  196. class VoiceRecordHUD: UIView {
  197. @IBInspectable var rate: CGFloat = 0.0
  198. @IBInspectable var fillColor: UIColor = UIColor.green {
  199. didSet {
  200. setNeedsDisplay()
  201. }
  202. }
  203. var image: UIImage! {
  204. didSet {
  205. setNeedsDisplay()
  206. }
  207. }
  208. override init(frame: CGRect) {
  209. super.init(frame: frame)
  210. image = UIImage(named: "microphone")
  211. }
  212. required init?(coder aDecoder: NSCoder) {
  213. super.init(coder: aDecoder)
  214. image = UIImage(named: "microphone")
  215. }
  216. func update(_ rate: CGFloat) {
  217. self.rate = rate
  218. setNeedsDisplay()
  219. }
  220. override func draw(_ rect: CGRect) {
  221. let context = UIGraphicsGetCurrentContext()
  222. context?.translateBy(x: 0, y: bounds.size.height)
  223. context?.scaleBy(x: 1, y: -1)
  224. context?.draw(image.cgImage!, in: bounds)
  225. context?.clip(to: bounds, mask: image.cgImage!)
  226. context?.setFillColor(fillColor.cgColor.components!)
  227. context?.fill(CGRect(x: 0, y: 0, width: bounds.width, height: bounds.height * rate))
  228. }
  229. override func prepareForInterfaceBuilder() {
  230. let bundle = Bundle(for: type(of: self))
  231. image = UIImage(named: "microphone", in: bundle, compatibleWith: self.traitCollection)
  232. }
  233. }