NCAudioRecorderViewController.swift 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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 Foundation
  27. import UIKit
  28. import AVFoundation
  29. import QuartzCore
  30. @objc protocol NCAudioRecorderViewControllerDelegate : class {
  31. func didFinishRecording(_ viewController: NCAudioRecorderViewController, fileName: String)
  32. func didFinishWithoutRecording(_ viewController: NCAudioRecorderViewController, fileName: String)
  33. }
  34. class NCAudioRecorderViewController: UIViewController , NCAudioRecorderDelegate {
  35. open weak var delegate: NCAudioRecorderViewControllerDelegate?
  36. var recording: NCAudioRecorder!
  37. var recordDuration: TimeInterval = 0
  38. var fileName: String = ""
  39. @IBOutlet weak var contentContainerView: UIView!
  40. @IBOutlet weak var durationLabel: UILabel!
  41. @IBOutlet weak var startStopLabel: UILabel!
  42. @IBOutlet weak var voiceRecordHUD: VoiceRecordHUD!
  43. // MARK: View Life Cycle
  44. override func viewDidLoad() {
  45. super.viewDidLoad()
  46. }
  47. override func viewWillAppear(_ animated: Bool) {
  48. super.viewWillAppear(animated)
  49. contentContainerView.backgroundColor = UIColor.lightGray
  50. voiceRecordHUD.update(0.0)
  51. voiceRecordHUD.fillColor = UIColor.green
  52. durationLabel.text = ""
  53. startStopLabel.text = NSLocalizedString("_voice_memo_start_", comment: "")
  54. }
  55. func createRecorder(fileName: String) {
  56. self.fileName = fileName
  57. recording = NCAudioRecorder(to: fileName)
  58. recording.delegate = self
  59. DispatchQueue.global().async {
  60. // Background thread
  61. do {
  62. try self.recording.prepare()
  63. } catch {
  64. print(error)
  65. }
  66. }
  67. }
  68. @IBAction func touchViewController() {
  69. if recording.state == .record {
  70. startStop()
  71. } else {
  72. dismiss(animated: true) {
  73. self.delegate?.didFinishWithoutRecording(self, fileName: self.fileName)
  74. }
  75. }
  76. }
  77. @IBAction func startStop() {
  78. if recording.state == .record {
  79. recordDuration = 0
  80. recording.stop()
  81. voiceRecordHUD.update(0.0)
  82. dismiss(animated: true) {
  83. self.delegate?.didFinishRecording(self, fileName: self.fileName)
  84. }
  85. } else {
  86. recordDuration = 0
  87. do {
  88. try recording.record()
  89. startStopLabel.text = NSLocalizedString("_voice_memo_stop_", comment: "")
  90. } catch {
  91. print(error)
  92. }
  93. }
  94. }
  95. func audioMeterDidUpdate(_ db: Float) {
  96. //print("db level: %f", db)
  97. self.recording.recorder?.updateMeters()
  98. let ALPHA = 0.05
  99. let peakPower = pow(10, (ALPHA * Double((self.recording.recorder?.peakPower(forChannel: 0))!)))
  100. var rate: Double = 0.0
  101. if (peakPower <= 0.2) {
  102. rate = 0.2
  103. } else if (peakPower > 0.9) {
  104. rate = 1.0
  105. } else {
  106. rate = peakPower
  107. }
  108. voiceRecordHUD.update(CGFloat(rate))
  109. voiceRecordHUD.fillColor = UIColor.green
  110. recordDuration += 1
  111. durationLabel.text = NCUtility.sharedInstance.formatSecondsToString(recordDuration/60)
  112. }
  113. }
  114. @objc public protocol NCAudioRecorderDelegate: AVAudioRecorderDelegate {
  115. @objc optional func audioMeterDidUpdate(_ dB: Float)
  116. }
  117. open class NCAudioRecorder : NSObject {
  118. @objc public enum State: Int {
  119. case none, record, play
  120. }
  121. static var directory: String {
  122. return NSTemporaryDirectory()
  123. }
  124. open weak var delegate: NCAudioRecorderDelegate?
  125. open fileprivate(set) var url: URL
  126. open fileprivate(set) var state: State = .none
  127. open var bitRate = 192000
  128. open var sampleRate = 44100.0
  129. open var channels = 1
  130. fileprivate let session = AVAudioSession.sharedInstance()
  131. var recorder: AVAudioRecorder?
  132. fileprivate var player: AVAudioPlayer?
  133. fileprivate var link: CADisplayLink?
  134. var metering: Bool {
  135. return delegate?.responds(to: #selector(NCAudioRecorderDelegate.audioMeterDidUpdate(_:))) == true
  136. }
  137. // MARK: - Initializers
  138. public init(to: String) {
  139. url = URL(fileURLWithPath: NCAudioRecorder.directory).appendingPathComponent(to)
  140. super.init()
  141. }
  142. // MARK: - Record
  143. open func prepare() throws {
  144. let settings: [String: AnyObject] = [
  145. AVFormatIDKey : NSNumber(value: Int32(kAudioFormatAppleLossless) as Int32),
  146. AVEncoderAudioQualityKey: AVAudioQuality.max.rawValue as AnyObject,
  147. AVEncoderBitRateKey: bitRate as AnyObject,
  148. AVNumberOfChannelsKey: channels as AnyObject,
  149. AVSampleRateKey: sampleRate as AnyObject
  150. ]
  151. recorder = try AVAudioRecorder(url: url, settings: settings)
  152. recorder?.prepareToRecord()
  153. recorder?.delegate = delegate
  154. recorder?.isMeteringEnabled = metering
  155. }
  156. open func record() throws {
  157. if recorder == nil {
  158. try prepare()
  159. }
  160. try session.setCategory(.playAndRecord, mode: .default)
  161. try session.overrideOutputAudioPort(AVAudioSession.PortOverride.speaker)
  162. recorder?.record()
  163. state = .record
  164. if metering {
  165. startMetering()
  166. }
  167. }
  168. open func play() throws {
  169. if recorder == nil {
  170. try prepare()
  171. }
  172. try session.setCategory(.playback, mode: .default)
  173. try AVAudioSession.sharedInstance().setActive(true)
  174. player = try AVAudioPlayer(contentsOf: url)
  175. player?.prepareToPlay()
  176. player?.play()
  177. state = .play
  178. }
  179. open func stop() {
  180. switch state {
  181. case .play:
  182. player?.stop()
  183. player = nil
  184. case .record:
  185. recorder?.stop()
  186. recorder = nil
  187. stopMetering()
  188. default:
  189. break
  190. }
  191. state = .none
  192. }
  193. // MARK: - Metering
  194. @objc func updateMeter() {
  195. guard let recorder = recorder else { return }
  196. recorder.updateMeters()
  197. let dB = recorder.averagePower(forChannel: 0)
  198. delegate?.audioMeterDidUpdate?(dB)
  199. }
  200. fileprivate func startMetering() {
  201. link = CADisplayLink(target: self, selector: #selector(NCAudioRecorder.updateMeter))
  202. link?.add(to: RunLoop.current, forMode: RunLoop.Mode.common)
  203. }
  204. fileprivate func stopMetering() {
  205. link?.invalidate()
  206. link = nil
  207. }
  208. }
  209. @IBDesignable
  210. class VoiceRecordHUD: UIView {
  211. @IBInspectable var rate: CGFloat = 0.0
  212. @IBInspectable var fillColor: UIColor = UIColor.green {
  213. didSet {
  214. setNeedsDisplay()
  215. }
  216. }
  217. var image: UIImage! {
  218. didSet {
  219. setNeedsDisplay()
  220. }
  221. }
  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. }