NCAudioRecorderViewController.swift 8.7 KB

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