NCAudioRecorderViewController.swift 9.5 KB

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