-
Notifications
You must be signed in to change notification settings - Fork 2
/
ViewModel.swift
230 lines (198 loc) · 7.52 KB
/
ViewModel.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
//
// Copyright 2021 Picovoice Inc.
// You may not use this file except in compliance with the license. A copy of the license is located in the "LICENSE"
// file accompanying this source.
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
// an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
//
import AVFoundation
import Foundation
import Octopus
enum UIState {
case INTRO
case RECORDING
case INDEXING
case NEW_SEARCH
case ZERO_SEARCH_RESULTS
case SEARCH_RESULTS
case FATAL_ERROR
}
class ViewModel: ObservableObject {
private let ACCESS_KEY = "{YOUR_ACCESS_KEY_HERE}"
private var octopus: Octopus!
private var metadata: OctopusMetadata!
private var recordingTimer = Timer()
private var audioRecorder: AVAudioRecorder!
private var isListening = false
private let MAX_RECORDING_LENGTH_SEC = 120.0
@Published var recordToggleButtonText: String = "Start"
@Published var searchPhraseText: String = ""
@Published var results: [OctopusMatch] = []
@Published var statusText = ""
@Published var showErrorAlert = false
@Published var errorAlertMessage = ""
@Published var errorMessage = ""
@Published var state: UIState = UIState.INTRO
@Published var isBusy: Bool = false
@Published var searchResultCountText: String = "# matches found"
@Published var recordingTimeSec = 0.0
init() {
isBusy = true
do {
try octopus = Octopus(accessKey: ACCESS_KEY)
statusText = "Start by recording some audio"
isBusy = false
} catch let error as OctopusInvalidArgumentError {
onOctopusInitFail("\(error.localizedDescription)")
} catch is OctopusActivationError {
errorMessage = "ACCESS_KEY activation error"
} catch is OctopusActivationRefusedError {
errorMessage = "ACCESS_KEY activation refused"
} catch is OctopusActivationLimitError {
errorMessage = "ACCESS_KEY reached its limit"
} catch is OctopusActivationThrottledError {
errorMessage = "ACCESS_KEY is throttled"
} catch {
errorMessage = "\(error)"
}
}
deinit {
do {
try stop()
} catch {
showErrorAlert("\(error)")
}
octopus.delete()
}
func onOctopusInitFail(_ initError: String) {
errorMessage = initError
state = UIState.FATAL_ERROR
}
public func toggleRecording() {
if isListening {
toggleRecordingOff()
} else {
toggleRecordingOn()
}
}
public func toggleRecordingOff() {
recordingTimer.invalidate()
statusText = ""
state = UIState.INDEXING
isBusy = true
DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
do {
try self.stop()
self.results = []
self.searchPhraseText = ""
self.state = UIState.NEW_SEARCH
self.statusText = "Try searching for a phrase in your recording"
} catch {
self.showErrorAlert("\(error)")
}
self.isBusy = false
}
}
public func toggleRecordingOn() {
isBusy = true
recordingTimeSec = 0
recordingTimer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { _ in
self.recordingTimeSec += 0.1
if self.recordingTimeSec > self.MAX_RECORDING_LENGTH_SEC {
self.toggleRecordingOff()
self.showErrorAlert("Recording exceeded max recording length")
}
}
DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
do {
try self.start()
self.statusText = "Recording..."
self.state = UIState.RECORDING
} catch {
self.showErrorAlert("\(error)")
}
self.isBusy = false
}
}
public func searchMetadata() {
let resign = #selector(UIResponder.resignFirstResponder)
UIApplication.shared.sendAction(resign, to: nil, from: nil, for: nil)
searchPhraseText = searchPhraseText.trimmingCharacters(in: .whitespacesAndNewlines)
guard !searchPhraseText.isEmpty else {
showErrorAlert("Search phrase cannot be empty")
return
}
do {
let searchResults = try octopus.search(metadata: metadata, phrases: Set([searchPhraseText]))
for (_, matches) in searchResults {
results = matches
for result in results {
print(result)
}
statusText = ""
if results.count == 0 {
searchResultCountText = "No matches found"
state = UIState.ZERO_SEARCH_RESULTS
} else {
let pluralMatch = results.count == 1 ? "match" : "matches"
searchResultCountText = "\(results.count) \(pluralMatch) found"
state = UIState.SEARCH_RESULTS
}
}
} catch let error as OctopusInvalidArgumentError {
showErrorAlert("\(error)")
} catch {
showErrorAlert("\(error)")
}
}
public func showErrorAlert(_ message: String) {
errorAlertMessage = message
showErrorAlert = true
}
public func start() throws {
guard !isListening else {
return
}
let audioSession = AVAudioSession.sharedInstance()
if audioSession.recordPermission == .denied {
errorMessage = "Recording permission is required for this demo"
state = UIState.FATAL_ERROR
statusText = ""
return
}
try audioSession.setActive(true)
try audioSession.setCategory(AVAudioSession.Category.playAndRecord,
options: [.mixWithOthers, .defaultToSpeaker, .allowBluetooth])
let documentPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let audioFilename = documentPath.appendingPathComponent("OctopusDemo.wav")
var formatDescription = AudioStreamBasicDescription(
mSampleRate: Float64(Octopus.pcmDataSampleRate),
mFormatID: kAudioFormatLinearPCM,
mFormatFlags: kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked,
mBytesPerPacket: 2,
mFramesPerPacket: 1,
mBytesPerFrame: 2,
mChannelsPerFrame: 1,
mBitsPerChannel: 16,
mReserved: 0)
let format = AVAudioFormat(streamDescription: &formatDescription)!
audioRecorder = try AVAudioRecorder(url: audioFilename, format: format)
audioRecorder.record()
isListening = true
}
public func stop() throws {
guard isListening else {
return
}
audioRecorder.stop()
isListening = false
let fileManager = FileManager.default
let documentDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
let directoryContents = try fileManager.contentsOfDirectory(
at: documentDirectory,
includingPropertiesForKeys: nil)
let path = directoryContents[0].path
metadata = try octopus.indexAudioFile(path: path)
}
}