-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOptionsViewController.swift
327 lines (258 loc) · 11.2 KB
/
OptionsViewController.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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
//
// OptionsViewController.swift
// Pinna
///
// Created by Matt Chen on 2022/3/20.
//
import UIKit
import Foundation
import AVFoundation
import UserNotifications
protocol OptionsViewControllerDelegate: class{
func play()
func toSetLow(value: Float)
func toSetMedium(value: Float)
func toSetHigh(value: Float)
}
let kVolume = "Volume"
class OptionsViewController: UIViewController {
var isPlayingLow = false
var isPlayingMedium = false
var isPlayingHigh = false
@IBOutlet weak var LowSlider: UISlider!
@IBOutlet weak var MediumSlider: UISlider!
@IBOutlet weak var HighSlider: UISlider!
weak var delegateOptionsViewController: OptionsViewControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
LowSlider.value = UserSetting.shared.low
MediumSlider.value = UserSetting.shared.medium
HighSlider.value = UserSetting.shared.high
}
override var prefersStatusBarHidden: Bool{
return true
}
@IBAction func toSetLow(_ sender: UISlider) {
UserSetting.shared.low = sender.value
delegateOptionsViewController?.toSetLow(value: sender.value)
print(UserSetting.shared.low)
}
@IBAction func toSetMedium(_ sender: UISlider) {
UserSetting.shared.medium = sender.value
delegateOptionsViewController?.toSetMedium(value: sender.value)
print(UserSetting.shared.medium)
}
@IBAction func toSetHigh(_ sender: UISlider) {
UserSetting.shared.high = sender.value
delegateOptionsViewController?.toSetLow(value: sender.value)
print(UserSetting.shared.high)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
@IBAction func playHigh(_ sender: UIButton) {
if !isPlayingHigh{
isPlayingHigh = !isPlayingHigh
playSound(expectedFrequency: 8000)
}
else{
isPlayingHigh = !isPlayingHigh
}
}
@IBAction func playMedium(_ sender: UIButton) {
if !isPlayingMedium{
isPlayingMedium = !isPlayingMedium
playSound(expectedFrequency: 2000)
}
else{
isPlayingMedium = !isPlayingMedium
}
}
@IBAction func playLow(_ sender: UIButton) {
if !isPlayingLow{
isPlayingLow = !isPlayingLow
playSound(expectedFrequency: 200)
}
else{
isPlayingLow = !isPlayingLow
}
}
@IBAction func pressDone(_ sender: UIButton) {
}
func playSound(expectedFrequency:Float){
let userDefaults = UserDefaults.standard
struct OptionNames {
static let signal = "signal"
static let frequency = "freq"
static let duration = "duration"
static let output = "output"
static let amplitude = "amplitude"
}
if CommandLine.arguments.contains("-help") || CommandLine.arguments.contains("-h") {
print("SignalGenerator\n")
print("Usage: SignalGenerator [-signal SIGNAL] [-freq FREQUENCY] [-duration DURATION] [-output FILEPATH] [-amplitude VALUE]\n")
print("Options:\n")
print("-\(OptionNames.signal) Type of signal: sine (default), square, sawtoothUp, sawtoothDown, triangle and noise")
print("-\(OptionNames.frequency) Frequncy in Hertz (defaut: 440)")
print("-\(OptionNames.duration) Duration in seconds (default: 5.0)")
print("-\(OptionNames.amplitude) Amplitude between 0.0 and 1.0 (default: 0.5)")
print("-\(OptionNames.output) Path to output file. If not set, no output file is written")
print("-help or -h Show this help\n")
exit(0)
}
let getFloatForKeyOrDefault = { (key: String, defaultValue: Float) -> Float in
let value = userDefaults.float(forKey: key)
return value > 0.0 ? value : defaultValue
}
let frequency = getFloatForKeyOrDefault(OptionNames.frequency, expectedFrequency)
let amplitude = min(max(getFloatForKeyOrDefault(OptionNames.amplitude, 0.5), 0.0), 1.0)
let duration = getFloatForKeyOrDefault(OptionNames.duration, 1)
let outputPath = userDefaults.string(forKey: OptionNames.output)
let twoPi = 2 * Float.pi
let sine = { (phase: Float) -> Float in
return sin(phase)
}
let whiteNoise = { (phase: Float) -> Float in
return ((Float(arc4random_uniform(UINT32_MAX)) / Float(UINT32_MAX)) * 2 - 1)
}
let sawtoothUp = { (phase: Float) -> Float in
return 1.0 - 2.0 * (phase * (1.0 / twoPi))
}
let sawtoothDown = { (phase: Float) -> Float in
return (2.0 * (phase * (1.0 / twoPi))) - 1.0
}
let square = { (phase: Float) -> Float in
if phase <= Float.pi {
return 1.0
} else {
return -1.0
}
}
let triangle = { (phase: Float) -> Float in
var value = (2.0 * (phase * (1.0 / twoPi))) - 1.0
if value < 0.0 {
value = -value
}
return 2.0 * (value - 0.5)
}
var signal: (Float) -> Float
if let signalName = userDefaults.string(forKey: OptionNames.signal) {
let signalFunctions = ["sine": sine,
"noise": whiteNoise,
"square": square,
"sawtoothUp": sawtoothUp,
"sawtoothDown": sawtoothDown,
"triangle": triangle]
if let signalFunction = signalFunctions[signalName] {
signal = signalFunction
} else {
print("Please specify a valid signal type: \(signalFunctions.keys.sorted().joined(separator: ", "))")
exit(1)
}
} else {
signal = sine
}
let engine = AVAudioEngine()
let mainMixer = engine.mainMixerNode
let output = engine.outputNode
let outputFormat = output.inputFormat(forBus: 0)
let sampleRate = Float(outputFormat.sampleRate)
// Use the output format for the input, but reduce the channel count to 1.
let inputFormat = AVAudioFormat(commonFormat: outputFormat.commonFormat,
sampleRate: outputFormat.sampleRate,
channels: 1,
interleaved: outputFormat.isInterleaved)
var currentPhase: Float = 0
// The interval to advance the phase each frame.
let phaseIncrement = (twoPi / sampleRate) * frequency
let srcNode = AVAudioSourceNode { _, _, frameCount, audioBufferList -> OSStatus in
let ablPointer = UnsafeMutableAudioBufferListPointer(audioBufferList)
for frame in 0..<Int(frameCount) {
// Get the signal value for this frame at time.
let value = signal(currentPhase) * amplitude
// Advance the phase for the next frame.
currentPhase += phaseIncrement
if currentPhase >= twoPi {
currentPhase -= twoPi
}
if currentPhase < 0.0 {
currentPhase += twoPi
}
// Set the same value on all channels (due to the inputFormat, there's only one channel though).
for buffer in ablPointer {
let buf: UnsafeMutableBufferPointer<Float> = UnsafeMutableBufferPointer(buffer)
buf[frame] = value
}
}
return noErr
}
engine.attach(srcNode)
engine.connect(srcNode, to: mainMixer, format: inputFormat)
engine.connect(mainMixer, to: output, format: outputFormat)
if expectedFrequency == 200{
mainMixer.outputVolume = UserSetting.shared.low
//UserSetting.shared.low
print(UserSetting.shared.low)
print(UserSetting.shared.medium)
}
else if expectedFrequency == 2000{
mainMixer.outputVolume = UserSetting.shared.medium
}
else{
mainMixer.outputVolume = UserSetting.shared.high
}
var outFile: AVAudioFile?
if let path = outputPath {
var samplesWritten: AVAudioFrameCount = 0
let outUrl = URL(fileURLWithPath: path).standardizedFileURL
let outDirExists = try? outUrl.deletingLastPathComponent().checkResourceIsReachable()
if outDirExists != nil {
var outputFormatSettings = srcNode.outputFormat(forBus: 0).settings
// Interleave the audio files.
outputFormatSettings[AVLinearPCMIsNonInterleaved] = false
outFile = try? AVAudioFile(forWriting: outUrl, settings: outputFormatSettings)
// Calculate the total number of samples to write for the duration.
let samplesToWrite = AVAudioFrameCount(duration * sampleRate)
srcNode.installTap(onBus: 0, bufferSize: 1024, format: inputFormat) { buffer, _ in
// Check whether to adjust the buffer frame length to match
// the requested number of samples.
if samplesWritten + buffer.frameLength > samplesToWrite {
buffer.frameLength = samplesToWrite - samplesWritten
}
do {
try outFile?.write(from: buffer)
} catch {
print("Error writing file \(error)")
}
samplesWritten += buffer.frameLength
// Exit the app after writing the requested number of samples.
if samplesWritten >= samplesToWrite {
CFRunLoopStop(CFRunLoopGetMain())
}
}
}
}
do {
try engine.start()
// When writing the output file, the run loop stops from the tap block
// after writing the number of samples for the requested duration.
// Otherwise, the app specifies the run duration of the run loop when it starts.
if outFile != nil {
CFRunLoopRun()
} else {
CFRunLoopRunInMode(.defaultMode, CFTimeInterval(duration), false)
}
engine.stop()
} catch {
print("Could not start engine: \(error)")
}
if isPlayingHigh||isPlayingMedium||isPlayingLow {
//DispatchQueue.main.asyncAfter(deadline: .now() + 0) {
self.playSound(expectedFrequency: expectedFrequency)
// }
}
}
}