NCAudioRecorderViewController.swift 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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. class NCAudioRecorderViewController: UIViewController, NCAudioRecorderDelegate {
  30. var recording: NCAudioRecorder!
  31. var startDate: Date = Date()
  32. var fileName: String = ""
  33. let appDelegate = (UIApplication.shared.delegate as? AppDelegate)!
  34. @IBOutlet weak var contentContainerView: UIView!
  35. @IBOutlet weak var durationLabel: UILabel!
  36. @IBOutlet weak var startStopLabel: UILabel!
  37. @IBOutlet weak var voiceRecordHUD: VoiceRecordHUD!
  38. // MARK: - View Life Cycle
  39. override func viewDidLoad() {
  40. super.viewDidLoad()
  41. voiceRecordHUD.update(0.0)
  42. durationLabel.text = ""
  43. startStopLabel.text = NSLocalizedString("_wait_", comment: "")
  44. view.backgroundColor = .clear
  45. contentContainerView.backgroundColor = UIColor.lightGray
  46. voiceRecordHUD.fillColor = UIColor.green
  47. Task {
  48. self.fileName = await NCNetworking.shared.createFileName(fileNameBase: NSLocalizedString("_untitled_", comment: "") + ".m4a", account: self.appDelegate.account, serverUrl: self.appDelegate.activeServerUrl)
  49. recording = NCAudioRecorder(to: self.fileName)
  50. recording.delegate = self
  51. do {
  52. try self.recording.prepare()
  53. startStopLabel.text = NSLocalizedString("_voice_memo_start_", comment: "")
  54. } catch {
  55. print(error)
  56. }
  57. }
  58. }
  59. // MARK: - Action
  60. @IBAction func touchViewController() {
  61. if recording.state == .record {
  62. startStop()
  63. } else {
  64. dismiss(animated: true)
  65. }
  66. }
  67. @IBAction func startStop() {
  68. if recording.state == .record {
  69. recording.stop()
  70. voiceRecordHUD.update(0.0)
  71. dismiss(animated: true) {
  72. self.uploadMetadata()
  73. }
  74. } else {
  75. do {
  76. try recording.record()
  77. startDate = Date()
  78. startStopLabel.text = NSLocalizedString("_voice_memo_stop_", comment: "")
  79. } catch {
  80. print(error)
  81. }
  82. }
  83. }
  84. func uploadMetadata() {
  85. let fileNamePath = NSTemporaryDirectory() + self.fileName
  86. let metadata = NCManageDatabase.shared.createMetadata(account: appDelegate.account, user: appDelegate.user, userId: appDelegate.userId, fileName: fileName, fileNameView: fileName, ocId: UUID().uuidString, serverUrl: appDelegate.activeServerUrl, urlBase: appDelegate.urlBase, url: "", contentType: "")
  87. metadata.session = NCNetworking.shared.sessionUploadBackground
  88. metadata.sessionSelector = NCGlobal.shared.selectorUploadFile
  89. metadata.status = NCGlobal.shared.metadataStatusWaitUpload
  90. metadata.sessionDate = Date()
  91. metadata.size = NCUtilityFileSystem().getFileSize(filePath: fileNamePath)
  92. NCUtilityFileSystem().copyFile(atPath: fileNamePath, toPath: NCUtilityFileSystem().getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  93. NCNetworkingProcess.shared.createProcessUploads(metadatas: [metadata])
  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. let formatter = DateComponentsFormatter()
  111. formatter.allowedUnits = [.second]
  112. formatter.unitsStyle = .full
  113. durationLabel.text = formatter.string(from: startDate, to: Date())
  114. }
  115. }
  116. @objc public protocol NCAudioRecorderDelegate: AVAudioRecorderDelegate {
  117. @objc optional func audioMeterDidUpdate(_ dB: Float)
  118. }
  119. open class NCAudioRecorder: NSObject {
  120. @objc public enum State: Int {
  121. case none, record, play
  122. }
  123. static var directory: String {
  124. return NSTemporaryDirectory()
  125. }
  126. open weak var delegate: NCAudioRecorderDelegate?
  127. open fileprivate(set) var url: URL
  128. open fileprivate(set) var state: State = .none
  129. open var bitRate = 192000
  130. open var sampleRate = 44100.0
  131. open var channels = 1
  132. var recorder: AVAudioRecorder?
  133. fileprivate var player: AVAudioPlayer?
  134. fileprivate var link: CADisplayLink?
  135. var metering: Bool {
  136. return delegate?.responds(to: #selector(NCAudioRecorderDelegate.audioMeterDidUpdate(_:))) == true
  137. }
  138. // MARK: - Initializers
  139. public init(to fileName: String) {
  140. url = URL(fileURLWithPath: NCAudioRecorder.directory).appendingPathComponent(fileName)
  141. super.init()
  142. do {
  143. try AVAudioSession.sharedInstance().setCategory(.playAndRecord)
  144. try AVAudioSession.sharedInstance().overrideOutputAudioPort(AVAudioSession.PortOverride.speaker)
  145. try AVAudioSession.sharedInstance().setActive(true)
  146. } catch {
  147. print(error)
  148. }
  149. }
  150. deinit {
  151. print("deinit NCAudioRecorder")
  152. do {
  153. try AVAudioSession.sharedInstance().setActive(false)
  154. } catch {
  155. print(error)
  156. }
  157. }
  158. // MARK: - Record
  159. open func prepare() throws {
  160. let settings: [String: AnyObject] = [
  161. AVFormatIDKey: NSNumber(value: Int32(kAudioFormatAppleLossless) as Int32),
  162. AVEncoderAudioQualityKey: AVAudioQuality.max.rawValue as AnyObject,
  163. AVEncoderBitRateKey: bitRate as AnyObject,
  164. AVNumberOfChannelsKey: channels as AnyObject,
  165. AVSampleRateKey: sampleRate as AnyObject
  166. ]
  167. recorder = try AVAudioRecorder(url: url, settings: settings)
  168. recorder?.prepareToRecord()
  169. recorder?.delegate = delegate
  170. recorder?.isMeteringEnabled = metering
  171. }
  172. open func record() throws {
  173. if recorder == nil {
  174. try prepare()
  175. }
  176. self.state = .record
  177. if self.metering {
  178. self.startMetering()
  179. }
  180. self.recorder?.record()
  181. }
  182. open func stop() {
  183. switch state {
  184. case .play:
  185. player?.stop()
  186. player = nil
  187. case .record:
  188. recorder?.stop()
  189. recorder = nil
  190. stopMetering()
  191. default:
  192. break
  193. }
  194. state = .none
  195. }
  196. // MARK: - Metering
  197. @objc func updateMeter() {
  198. guard let recorder = recorder else { return }
  199. recorder.updateMeters()
  200. let dB = recorder.averagePower(forChannel: 0)
  201. delegate?.audioMeterDidUpdate?(dB)
  202. }
  203. fileprivate func startMetering() {
  204. link = CADisplayLink(target: self, selector: #selector(NCAudioRecorder.updateMeter))
  205. link?.add(to: RunLoop.current, forMode: RunLoop.Mode.common)
  206. }
  207. fileprivate func stopMetering() {
  208. link?.invalidate()
  209. link = nil
  210. }
  211. }
  212. @IBDesignable
  213. class VoiceRecordHUD: UIView {
  214. @IBInspectable var rate: CGFloat = 0.0
  215. @IBInspectable var fillColor: UIColor = UIColor.green {
  216. didSet {
  217. setNeedsDisplay()
  218. }
  219. }
  220. var image: UIImage! {
  221. didSet {
  222. setNeedsDisplay()
  223. }
  224. }
  225. // MARK: - View Life Cycle
  226. override init(frame: CGRect) {
  227. super.init(frame: frame)
  228. image = UIImage(named: "microphone")
  229. }
  230. required init?(coder aDecoder: NSCoder) {
  231. super.init(coder: aDecoder)
  232. image = UIImage(named: "microphone")
  233. }
  234. func update(_ rate: CGFloat) {
  235. self.rate = rate
  236. setNeedsDisplay()
  237. }
  238. override func draw(_ rect: CGRect) {
  239. let context = UIGraphicsGetCurrentContext()
  240. context?.translateBy(x: 0, y: bounds.size.height)
  241. context?.scaleBy(x: 1, y: -1)
  242. context?.draw(image.cgImage!, in: bounds)
  243. context?.clip(to: bounds, mask: image.cgImage!)
  244. context?.setFillColor(fillColor.cgColor.components!)
  245. context?.fill(CGRect(x: 0, y: 0, width: bounds.width, height: bounds.height * rate))
  246. }
  247. override func prepareForInterfaceBuilder() {
  248. let bundle = Bundle(for: type(of: self))
  249. image = UIImage(named: "microphone", in: bundle, compatibleWith: self.traitCollection)
  250. }
  251. }