NCAudioRecorderViewController.swift 8.1 KB

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