@blotch/angular-lynx-native 22.3.2 → 22.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -2
- package/dist/android/project.d.ts +27 -3
- package/dist/android/project.d.ts.map +1 -1
- package/dist/android/project.js +80 -9
- package/dist/eject.d.ts.map +1 -1
- package/dist/eject.js +1 -0
- package/dist/files.d.ts +24 -0
- package/dist/files.d.ts.map +1 -0
- package/dist/files.js +41 -0
- package/dist/generate.d.ts +17 -2
- package/dist/generate.d.ts.map +1 -1
- package/dist/generate.js +68 -17
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -1
- package/dist/ios/project.d.ts +21 -2
- package/dist/ios/project.d.ts.map +1 -1
- package/dist/ios/project.js +58 -2
- package/dist/options.d.ts +68 -0
- package/dist/options.d.ts.map +1 -1
- package/dist/options.js +27 -0
- package/dist/permissions.d.ts.map +1 -1
- package/dist/permissions.js +18 -3
- package/dist/plugins.d.ts +245 -0
- package/dist/plugins.d.ts.map +1 -0
- package/dist/plugins.js +1244 -0
- package/package.json +1 -1
- package/templates/android/README.md +12 -4
- package/templates/android/app/build.gradle.kts +27 -9
- package/templates/android/app/src/main/AndroidManifest.xml +5 -0
- package/templates/android/app/src/main/java/dev/angularlynx/shell/AngularLynxPlugins.kt +13 -0
- package/templates/android/app/src/main/java/dev/angularlynx/shell/AudioRecorderModule.kt +520 -0
- package/templates/android/app/src/main/java/dev/angularlynx/shell/EdgeToEdgeOverlay.kt +24 -0
- package/templates/android/app/src/main/java/dev/angularlynx/shell/EngineThreadHint.kt +156 -0
- package/templates/android/app/src/main/java/dev/angularlynx/shell/GeolocationModule.kt +557 -0
- package/templates/android/app/src/main/java/dev/angularlynx/shell/HostElementUI.kt +331 -0
- package/templates/android/app/src/main/java/dev/angularlynx/shell/ImagePickerModule.kt +143 -0
- package/templates/android/app/src/main/java/dev/angularlynx/shell/ImagePipeline.kt +83 -0
- package/templates/android/app/src/main/java/dev/angularlynx/shell/MainActivity.kt +153 -9
- package/templates/android/app/src/main/java/dev/angularlynx/shell/NetworkStatus.kt +121 -0
- package/templates/android/app/src/main/java/dev/angularlynx/shell/PermissionRequests.kt +10 -0
- package/templates/android/app/src/main/java/dev/angularlynx/shell/PhotoLibraryModule.kt +203 -16
- package/templates/android/app/src/main/java/dev/angularlynx/shell/ShellApplication.kt +1 -8
- package/templates/android/app/src/main/java/dev/angularlynx/shell/ShellModule.kt +11 -1
- package/templates/android/app/src/main/res/xml/share_paths.xml +7 -2
- package/templates/ios/App/AngularLynxPlugins.swift +22 -0
- package/templates/ios/App/AnimationFrameRate.swift +66 -0
- package/templates/ios/App/AppDelegate.swift +3 -1
- package/templates/ios/App/AudioRecorderModule.swift +433 -0
- package/templates/ios/App/GeolocationModule.swift +455 -0
- package/templates/ios/App/HostElementUI.swift +270 -0
- package/templates/ios/App/ImagePickerModule.swift +160 -1
- package/templates/ios/App/LynxViewController.swift +66 -5
- package/templates/ios/App/NetworkStatus.swift +41 -0
|
@@ -0,0 +1,433 @@
|
|
|
1
|
+
import AVFoundation
|
|
2
|
+
import Foundation
|
|
3
|
+
import Lynx
|
|
4
|
+
import UIKit
|
|
5
|
+
|
|
6
|
+
/// The native module behind the runtime's `LynxAudioRecorder`, which calls it
|
|
7
|
+
/// as `NativeModules.AngularLynxAudioRecorder` (from the background thread,
|
|
8
|
+
/// where NativeModules lives). Android's shell has one of the same name.
|
|
9
|
+
///
|
|
10
|
+
/// It records AAC into an `.m4a` file in the app's temporary folder with
|
|
11
|
+
/// `AVAudioRecorder`, one recording at a time:
|
|
12
|
+
///
|
|
13
|
+
/// - `permission` calls back `{ permission }`: `granted`, `denied` or
|
|
14
|
+
/// `undetermined`, without asking.
|
|
15
|
+
/// - `requestPermission` asks, if the person hasn't been asked, and calls back
|
|
16
|
+
/// `{ permission }` once they answer.
|
|
17
|
+
/// - `start` takes `{ recording, maxDuration? }`, asks first if it needs to,
|
|
18
|
+
/// and calls back `{}` once it records, or `{ error, message }`: `denied`,
|
|
19
|
+
/// `busy` while another recording is open, or `failed`.
|
|
20
|
+
/// - `pause` and `resume` call back `{}`.
|
|
21
|
+
/// - `stop` ends the recording and calls back `{ clip }`: `{ uri, name,
|
|
22
|
+
/// durationMs, mimeType, size }`. Once it ended by itself, it calls back
|
|
23
|
+
/// with that clip.
|
|
24
|
+
/// - `cancel` ends it and deletes the file.
|
|
25
|
+
/// - `read` takes `{ uri }` and calls back `{ base64 }`, the bytes of a clip
|
|
26
|
+
/// this module recorded.
|
|
27
|
+
///
|
|
28
|
+
/// What the app didn't ask for at that moment arrives as the
|
|
29
|
+
/// `angularLynxAudioRecorder` global event, carrying the `recording` id
|
|
30
|
+
/// `start` was given: `level` about ten times a second while it records
|
|
31
|
+
/// (`{ level, durationMs }`), `paused` when the system paused it (a phone
|
|
32
|
+
/// call, Siri, or the app going to the background, since it records in the
|
|
33
|
+
/// foreground only), and `ended` once it reached `maxDuration` (`{ clip }`)
|
|
34
|
+
/// or failed (`{ error, message }`).
|
|
35
|
+
///
|
|
36
|
+
/// App Store Connect flags an app whose code uses the microphone without
|
|
37
|
+
/// `NSMicrophoneUsageDescription` (ITMS-90683), which the generator writes
|
|
38
|
+
/// only for an app whose angular.json sets `permissions.microphone`, so it
|
|
39
|
+
/// keeps this file only then, and LynxViewController registers the class by
|
|
40
|
+
/// its Objective-C name instead of naming it.
|
|
41
|
+
///
|
|
42
|
+
/// Everything here, the methods Lynx calls on its JavaScript thread, the
|
|
43
|
+
/// meter's timer and the session's notifications, runs on `queue`, so the
|
|
44
|
+
/// state needs no lock.
|
|
45
|
+
@objc(AngularLynxAudioRecorderModule)
|
|
46
|
+
final class AudioRecorderModule: NSObject, LynxContextModule, AVAudioRecorderDelegate {
|
|
47
|
+
static var name: String { "AngularLynxAudioRecorder" }
|
|
48
|
+
|
|
49
|
+
static let eventName = "angularLynxAudioRecorder"
|
|
50
|
+
|
|
51
|
+
static var methodLookup: [String: String] {
|
|
52
|
+
[
|
|
53
|
+
"permission": NSStringFromSelector(#selector(permission(_:))),
|
|
54
|
+
"requestPermission": NSStringFromSelector(#selector(requestPermission(_:))),
|
|
55
|
+
"start": NSStringFromSelector(#selector(start(_:callback:))),
|
|
56
|
+
"pause": NSStringFromSelector(#selector(pause(_:))),
|
|
57
|
+
"resume": NSStringFromSelector(#selector(resume(_:))),
|
|
58
|
+
"stop": NSStringFromSelector(#selector(stop(_:))),
|
|
59
|
+
"cancel": NSStringFromSelector(#selector(cancel(_:))),
|
|
60
|
+
"read": NSStringFromSelector(#selector(read(_:callback:))),
|
|
61
|
+
]
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/// How often the meter is read and sent, in seconds.
|
|
65
|
+
private static let levelInterval = 0.1
|
|
66
|
+
/// The quietest level a meter shows, in dBFS: the runtime's 0.
|
|
67
|
+
private static let levelFloor: Float = -60
|
|
68
|
+
|
|
69
|
+
private weak var context: LynxContext?
|
|
70
|
+
private let queue = DispatchQueue(label: "dev.angularlynx.audio-recorder")
|
|
71
|
+
private lazy var notifications: OperationQueue = {
|
|
72
|
+
let operations = OperationQueue()
|
|
73
|
+
operations.underlyingQueue = queue
|
|
74
|
+
operations.maxConcurrentOperationCount = 1
|
|
75
|
+
return operations
|
|
76
|
+
}()
|
|
77
|
+
private var observers: [NSObjectProtocol] = []
|
|
78
|
+
|
|
79
|
+
private struct Recording {
|
|
80
|
+
let id: Int
|
|
81
|
+
let recorder: AVAudioRecorder
|
|
82
|
+
let url: URL
|
|
83
|
+
let maxDuration: TimeInterval?
|
|
84
|
+
/// How long it recorded before its latest start or resume.
|
|
85
|
+
var recorded: TimeInterval = 0
|
|
86
|
+
/// When it last started or resumed, by the system's uptime (which the
|
|
87
|
+
/// clock being set can't move), or nil while it's paused.
|
|
88
|
+
var since: TimeInterval? = ProcessInfo.processInfo.systemUptime
|
|
89
|
+
/// What the audio session was before this recording, which it puts back.
|
|
90
|
+
let previous: (AVAudioSession.Category, AVAudioSession.Mode, AVAudioSession.CategoryOptions)
|
|
91
|
+
|
|
92
|
+
var elapsed: TimeInterval {
|
|
93
|
+
recorded + (since.map { ProcessInfo.processInfo.systemUptime - $0 } ?? 0)
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
private var recording: Recording?
|
|
98
|
+
/// The clip of the recording that ended by itself, for the `stop` after it.
|
|
99
|
+
private var ended: [String: Any]?
|
|
100
|
+
private var timer: DispatchSourceTimer?
|
|
101
|
+
|
|
102
|
+
override init() {
|
|
103
|
+
super.init()
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// Swift can't import an optional initializer as optional, so Lynx's
|
|
107
|
+
// initWithParam: and initWithLynxContext:WithParam: are required here.
|
|
108
|
+
init(param: Any) {
|
|
109
|
+
super.init()
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
init(lynxContext context: LynxContext) {
|
|
113
|
+
self.context = context
|
|
114
|
+
super.init()
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
init(lynxContext context: LynxContext, withParam param: Any) {
|
|
118
|
+
self.context = context
|
|
119
|
+
super.init()
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
deinit {
|
|
123
|
+
for observer in observers { NotificationCenter.default.removeObserver(observer) }
|
|
124
|
+
timer?.cancel()
|
|
125
|
+
// The page closed mid-recording: nobody can have the clip, and the next
|
|
126
|
+
// page shouldn't inherit the recording's session.
|
|
127
|
+
if let current = recording {
|
|
128
|
+
current.recorder.stop()
|
|
129
|
+
current.recorder.deleteRecording()
|
|
130
|
+
restore(current.previous)
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// MARK: - Permission
|
|
135
|
+
|
|
136
|
+
@objc func permission(_ callback: @escaping LynxCallbackBlock) {
|
|
137
|
+
callback(["permission": Self.currentPermission()])
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
@objc func requestPermission(_ callback: @escaping LynxCallbackBlock) {
|
|
141
|
+
Self.ask { _ in callback(["permission": Self.currentPermission()]) }
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
private static func currentPermission() -> String {
|
|
145
|
+
if #available(iOS 17.0, *) {
|
|
146
|
+
switch AVAudioApplication.shared.recordPermission {
|
|
147
|
+
case .granted: return "granted"
|
|
148
|
+
case .denied: return "denied"
|
|
149
|
+
default: return "undetermined"
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
switch AVAudioSession.sharedInstance().recordPermission {
|
|
153
|
+
case .granted: return "granted"
|
|
154
|
+
case .denied: return "denied"
|
|
155
|
+
default: return "undetermined"
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/// Shows iOS's microphone prompt, with the app's
|
|
160
|
+
/// NSMicrophoneUsageDescription, unless the person has answered it before.
|
|
161
|
+
private static func ask(_ done: @escaping (Bool) -> Void) {
|
|
162
|
+
if #available(iOS 17.0, *) {
|
|
163
|
+
AVAudioApplication.requestRecordPermission(completionHandler: done)
|
|
164
|
+
} else {
|
|
165
|
+
AVAudioSession.sharedInstance().requestRecordPermission(done)
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// MARK: - Recording
|
|
170
|
+
|
|
171
|
+
@objc func start(_ options: [String: Any], callback: @escaping LynxCallbackBlock) {
|
|
172
|
+
Self.ask { [weak self] granted in
|
|
173
|
+
guard let self else { return }
|
|
174
|
+
self.queue.async {
|
|
175
|
+
guard granted else {
|
|
176
|
+
callback(Self.failure("denied", "The person didn't allow the microphone."))
|
|
177
|
+
return
|
|
178
|
+
}
|
|
179
|
+
callback(self.begin(options))
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
private func begin(_ options: [String: Any]) -> [String: Any] {
|
|
185
|
+
if recording != nil {
|
|
186
|
+
return Self.failure("busy", "Another recording is still open: stop it first.")
|
|
187
|
+
}
|
|
188
|
+
let id = (options["recording"] as? NSNumber)?.intValue ?? 0
|
|
189
|
+
let maxDuration = (options["maxDuration"] as? NSNumber).map { $0.doubleValue / 1000 }
|
|
190
|
+
let session = AVAudioSession.sharedInstance()
|
|
191
|
+
let previous = (session.category, session.mode, session.categoryOptions)
|
|
192
|
+
let folder = FileManager.default.temporaryDirectory.appendingPathComponent(
|
|
193
|
+
"recordings", isDirectory: true)
|
|
194
|
+
let name = "recording-\(Int(Date().timeIntervalSince1970 * 1000)).m4a"
|
|
195
|
+
let url = folder.appendingPathComponent(name)
|
|
196
|
+
do {
|
|
197
|
+
// playAndRecord rather than record, so what the app plays (a
|
|
198
|
+
// recording's playback, a sound) isn't silenced while it records,
|
|
199
|
+
// through the speaker rather than the earpiece.
|
|
200
|
+
try session.setCategory(
|
|
201
|
+
.playAndRecord, mode: .default, options: [.defaultToSpeaker, .allowBluetooth])
|
|
202
|
+
try session.setActive(true)
|
|
203
|
+
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
|
|
204
|
+
let recorder = try AVAudioRecorder(
|
|
205
|
+
url: url,
|
|
206
|
+
settings: [
|
|
207
|
+
AVFormatIDKey: kAudioFormatMPEG4AAC,
|
|
208
|
+
AVSampleRateKey: 44_100,
|
|
209
|
+
AVNumberOfChannelsKey: 1,
|
|
210
|
+
// Enough for a voice, at a fraction of music's bit rate.
|
|
211
|
+
AVEncoderBitRateKey: 64_000,
|
|
212
|
+
AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue,
|
|
213
|
+
])
|
|
214
|
+
recorder.delegate = self
|
|
215
|
+
recorder.isMeteringEnabled = true
|
|
216
|
+
guard recorder.record() else {
|
|
217
|
+
restore(previous)
|
|
218
|
+
return Self.failure(
|
|
219
|
+
"busy", "The microphone is in use: another app may be recording, or a call is on.")
|
|
220
|
+
}
|
|
221
|
+
recording = Recording(
|
|
222
|
+
id: id, recorder: recorder, url: url, maxDuration: maxDuration, previous: previous)
|
|
223
|
+
ended = nil
|
|
224
|
+
watch()
|
|
225
|
+
startMeter()
|
|
226
|
+
return [:]
|
|
227
|
+
} catch {
|
|
228
|
+
restore(previous)
|
|
229
|
+
return Self.failure("failed", error.localizedDescription)
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
@objc func pause(_ callback: @escaping LynxCallbackBlock) {
|
|
234
|
+
queue.async {
|
|
235
|
+
self.pauseRecording()
|
|
236
|
+
callback([:])
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
@objc func resume(_ callback: @escaping LynxCallbackBlock) {
|
|
241
|
+
queue.async {
|
|
242
|
+
guard var current = self.recording, current.since == nil else {
|
|
243
|
+
callback([:])
|
|
244
|
+
return
|
|
245
|
+
}
|
|
246
|
+
// The session may have been taken by a call meanwhile.
|
|
247
|
+
try? AVAudioSession.sharedInstance().setActive(true)
|
|
248
|
+
guard current.recorder.record() else {
|
|
249
|
+
callback(
|
|
250
|
+
Self.failure(
|
|
251
|
+
"busy", "The microphone is in use: another app may be recording, or a call is on."))
|
|
252
|
+
return
|
|
253
|
+
}
|
|
254
|
+
current.since = ProcessInfo.processInfo.systemUptime
|
|
255
|
+
self.recording = current
|
|
256
|
+
callback([:])
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
@objc func stop(_ callback: @escaping LynxCallbackBlock) {
|
|
261
|
+
queue.async {
|
|
262
|
+
if let clip = self.finish() {
|
|
263
|
+
callback(["clip": clip])
|
|
264
|
+
} else if let clip = self.ended {
|
|
265
|
+
callback(["clip": clip])
|
|
266
|
+
} else {
|
|
267
|
+
callback(Self.failure("failed", "Nothing is recording."))
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
@objc func cancel(_ callback: @escaping LynxCallbackBlock) {
|
|
273
|
+
queue.async {
|
|
274
|
+
if let current = self.recording {
|
|
275
|
+
self.recording = nil
|
|
276
|
+
// Stopped before the session is let go, which would stop it anyway.
|
|
277
|
+
current.recorder.stop()
|
|
278
|
+
current.recorder.deleteRecording()
|
|
279
|
+
self.release(current)
|
|
280
|
+
}
|
|
281
|
+
self.ended = nil
|
|
282
|
+
callback([:])
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
@objc func read(_ options: [String: Any], callback: @escaping LynxCallbackBlock) {
|
|
287
|
+
queue.async {
|
|
288
|
+
let folder = FileManager.default.temporaryDirectory.appendingPathComponent(
|
|
289
|
+
"recordings", isDirectory: true
|
|
290
|
+
).standardizedFileURL.path
|
|
291
|
+
// Only this module's own recordings: the runtime gives back the uri it
|
|
292
|
+
// was handed, and the module reads no other file.
|
|
293
|
+
guard let text = options["uri"] as? String, let url = URL(string: text), url.isFileURL,
|
|
294
|
+
url.standardizedFileURL.deletingLastPathComponent().path == folder,
|
|
295
|
+
let data = try? Data(contentsOf: url)
|
|
296
|
+
else {
|
|
297
|
+
callback(Self.failure("failed", "The recording couldn't be read."))
|
|
298
|
+
return
|
|
299
|
+
}
|
|
300
|
+
callback(["base64": data.base64EncodedString()])
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
// MARK: - Helpers
|
|
305
|
+
|
|
306
|
+
private func pauseRecording() {
|
|
307
|
+
guard var current = recording, current.since != nil else { return }
|
|
308
|
+
current.recorder.pause()
|
|
309
|
+
current.recorded = current.elapsed
|
|
310
|
+
current.since = nil
|
|
311
|
+
recording = current
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/// Stops the recording, puts the session back and describes its file.
|
|
315
|
+
private func finish() -> [String: Any]? {
|
|
316
|
+
guard let current = recording else { return nil }
|
|
317
|
+
let durationMs = Int((current.elapsed * 1000).rounded())
|
|
318
|
+
recording = nil
|
|
319
|
+
current.recorder.stop()
|
|
320
|
+
release(current)
|
|
321
|
+
let size =
|
|
322
|
+
(try? FileManager.default.attributesOfItem(atPath: current.url.path)[.size] as? NSNumber)?
|
|
323
|
+
.intValue ?? 0
|
|
324
|
+
return [
|
|
325
|
+
"uri": current.url.absoluteString,
|
|
326
|
+
"name": current.url.lastPathComponent,
|
|
327
|
+
"durationMs": durationMs,
|
|
328
|
+
"mimeType": "audio/mp4",
|
|
329
|
+
"size": size,
|
|
330
|
+
]
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
private func release(_ current: Recording) {
|
|
334
|
+
timer?.cancel()
|
|
335
|
+
timer = nil
|
|
336
|
+
for observer in observers { NotificationCenter.default.removeObserver(observer) }
|
|
337
|
+
observers = []
|
|
338
|
+
restore(current.previous)
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/// Puts the audio session back as the recording found it, and lets the
|
|
342
|
+
/// app that was playing (music, a podcast) carry on. Called once the
|
|
343
|
+
/// recorder has stopped. Deactivating also stops what this app plays
|
|
344
|
+
/// through the session, but the shell plays nothing through it itself, and
|
|
345
|
+
/// another app's music resuming after a voice note matters more.
|
|
346
|
+
private func restore(
|
|
347
|
+
_ previous: (AVAudioSession.Category, AVAudioSession.Mode, AVAudioSession.CategoryOptions)
|
|
348
|
+
) {
|
|
349
|
+
let session = AVAudioSession.sharedInstance()
|
|
350
|
+
try? session.setActive(false, options: .notifyOthersOnDeactivation)
|
|
351
|
+
try? session.setCategory(previous.0, mode: previous.1, options: previous.2)
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/// The system pausing the recording: a call or Siri taking the session,
|
|
355
|
+
/// or the app going to the background, where it may not record.
|
|
356
|
+
private func watch() {
|
|
357
|
+
let center = NotificationCenter.default
|
|
358
|
+
observers = [
|
|
359
|
+
center.addObserver(
|
|
360
|
+
forName: AVAudioSession.interruptionNotification, object: nil, queue: notifications
|
|
361
|
+
) { [weak self] note in
|
|
362
|
+
let type = (note.userInfo?[AVAudioSessionInterruptionTypeKey] as? NSNumber)
|
|
363
|
+
.flatMap { AVAudioSession.InterruptionType(rawValue: $0.uintValue) }
|
|
364
|
+
if type == .began { self?.systemPaused() }
|
|
365
|
+
},
|
|
366
|
+
center.addObserver(
|
|
367
|
+
forName: UIApplication.didEnterBackgroundNotification, object: nil, queue: notifications
|
|
368
|
+
) { [weak self] _ in self?.systemPaused() },
|
|
369
|
+
]
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
private func systemPaused() {
|
|
373
|
+
guard let current = recording, current.since != nil else { return }
|
|
374
|
+
pauseRecording()
|
|
375
|
+
send(["type": "paused", "recording": current.id])
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
private func startMeter() {
|
|
379
|
+
let source = DispatchSource.makeTimerSource(queue: queue)
|
|
380
|
+
source.schedule(deadline: .now() + Self.levelInterval, repeating: Self.levelInterval)
|
|
381
|
+
source.setEventHandler { [weak self] in self?.tick() }
|
|
382
|
+
timer = source
|
|
383
|
+
source.resume()
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
private func tick() {
|
|
387
|
+
guard let current = recording, current.since != nil else { return }
|
|
388
|
+
let elapsed = current.elapsed
|
|
389
|
+
if let maxDuration = current.maxDuration, elapsed >= maxDuration, let clip = finish() {
|
|
390
|
+
ended = clip
|
|
391
|
+
send(["type": "ended", "recording": current.id, "clip": clip])
|
|
392
|
+
return
|
|
393
|
+
}
|
|
394
|
+
current.recorder.updateMeters()
|
|
395
|
+
let power = current.recorder.averagePower(forChannel: 0)
|
|
396
|
+
let level = max(0, min(1, (power - Self.levelFloor) / -Self.levelFloor))
|
|
397
|
+
send([
|
|
398
|
+
"type": "level", "recording": current.id, "level": level,
|
|
399
|
+
"durationMs": Int((elapsed * 1000).rounded()),
|
|
400
|
+
])
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
// AVAudioRecorder ends a recording itself only when encoding fails, or the
|
|
404
|
+
// disk fills.
|
|
405
|
+
func audioRecorderEncodeErrorDidOccur(_ recorder: AVAudioRecorder, error: Error?) {
|
|
406
|
+
queue.async {
|
|
407
|
+
guard let current = self.recording, current.recorder === recorder else { return }
|
|
408
|
+
self.recording = nil
|
|
409
|
+
// Nobody can have a clip of it, so its file goes too.
|
|
410
|
+
current.recorder.stop()
|
|
411
|
+
current.recorder.deleteRecording()
|
|
412
|
+
self.release(current)
|
|
413
|
+
self.send(
|
|
414
|
+
[
|
|
415
|
+
"type": "ended", "recording": current.id, "error": "failed",
|
|
416
|
+
"message": error?.localizedDescription ?? "The recording couldn't be encoded.",
|
|
417
|
+
])
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
|
|
422
|
+
guard !flag else { return }
|
|
423
|
+
audioRecorderEncodeErrorDidOccur(recorder, error: nil)
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
private func send(_ payload: [String: Any]) {
|
|
427
|
+
context?.sendGlobalEvent(Self.eventName, withParams: [payload])
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
private static func failure(_ code: String, _ message: String) -> [String: Any] {
|
|
431
|
+
["error": code, "message": message]
|
|
432
|
+
}
|
|
433
|
+
}
|