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