-
Notifications
You must be signed in to change notification settings - Fork 12
/
CephalopodDistrib.swift
351 lines (253 loc) · 10.6 KB
/
CephalopodDistrib.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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
//
// A sound fader for AvAudioPlayer written in Swift for iOS, tvOS and macOS.
//
// https://github.com/evgenyneu/Cephalopod
//
// This file was automatically generated by combining multiple Swift source files.
//
// ----------------------------
//
// AutoCancellingTimer.swift
//
// ----------------------------
//
// Creates a timer that executes code after delay. The timer lives in an instance of `AutoCancellingTimer` class and is automatically canceled when this instance is deallocated.
// This is an auto-canceling alternative to timer created with `dispatch_after` function.
//
// Source: https://gist.github.com/evgenyneu/516f7dcdb5f2f73d7923
//
// Usage
// -----
//
// class MyClass {
// var timer: AutoCancellingTimer? // Timer will be cancelled with MyCall is deallocated
//
// func runTimer() {
// timer = AutoCancellingTimer(interval: delaySeconds, repeats: true) {
// ... code to run
// }
// }
// }
//
//
// Cancel the timer
// --------------------
//
// Timer is canceled automatically when it is deallocated. You can also cancel it manually:
//
// timer.cancel()
//
import Foundation
final class AutoCancellingTimer {
private var timer: AutoCancellingTimerInstance?
init(interval: TimeInterval, repeats: Bool = false, callback: @escaping ()->()) {
timer = AutoCancellingTimerInstance(interval: interval, repeats: repeats, callback: callback)
}
deinit {
timer?.cancel()
}
func cancel() {
timer?.cancel()
}
}
final class AutoCancellingTimerInstance: NSObject {
private let repeats: Bool
private var timer: Timer?
private var callback: ()->()
init(interval: TimeInterval, repeats: Bool = false, callback: @escaping ()->()) {
self.repeats = repeats
self.callback = callback
super.init()
timer = Timer.scheduledTimer(timeInterval: interval, target: self,
selector: #selector(AutoCancellingTimerInstance.timerFired(_:)), userInfo: nil, repeats: repeats)
}
func cancel() {
timer?.invalidate()
}
@objc func timerFired(_ timer: Timer) {
self.callback()
if !repeats { cancel() }
}
}
// ----------------------------
//
// Cephalopod.swift
//
// ----------------------------
import Foundation
import AVFoundation
/**
A sound fader for AvAudioPlayer written in Swift - iOS, tvOS and macOS.
Usage
--------
import AVFoundation
import Cephalopod // For CocoaPods and Carthage
// ---
var playerInstance: AVAudioPlayer?
var cephalopod: Cephalopod?
override func viewDidLoad() {
super.viewDidLoad()
// Create player instance
guard let path = Bundle.main.path(forResource: "squid", ofType: "mp3") else { return }
guard let player = try? AVAudioPlayer(contentsOf: URL(fileURLWithPath: path)) else { return }
playerInstance = player
// Start audio playback
player.play()
player.volume = 0
// Fade in the sound
cephalopod = Cephalopod(player: player)
cephalopod?.fadeIn()
}
*/
open class Cephalopod: NSObject {
/**
Changes the quality of the fade effect. The higher number means the higher the quality of fade. Higher values consume more CPU resources. Default: 30.
*/
open var volumeAlterationsPerSecond = 30.0
/// Default duration of the fade effect
public static let defaultFadeDurationSeconds = 3.0
/// Default velocity of the fade effect
public static let defaultVelocity = 2.0
let player: AVAudioPlayer
var timer: AutoCancellingTimer?
private var fadeDurationSeconds = defaultFadeDurationSeconds
private var fadeVelocity = defaultVelocity
private var fromVolume = 0.0
private var toVolume = 0.0
private var currentStep = 0
private var onFinished: ((Bool)->())? = nil
/**
Instantiate a cephalopod fader object.
- parameter player: an instance of AVAudioPlayer.
*/
public init(player: AVAudioPlayer) {
self.player = player
}
deinit {
callOnFinished(finished: false)
stop()
}
/**
Fade in the sound by gradually increasing the volume.
- parameter duration: duration of the fade, in seconds. Default duration: 3 seconds.
- parameter velocity: a number specifying how fast the sound volume is changing. Velocity of 0 creates a linear fade. Values greater than zero produce more exponential fade affect. Exponential fade sounds more gradual to a human ear. The fade sounds most natural with velocity parameter from 2 to 5. Default value: 2.
- parameter onFinished: an optional closure that will be called after the fade has ended. The closure will be passed a boolean parameter `finished` indicating whether the fading has reached its end value (true) or if the fading has been cancelled (false).
*/
open func fadeIn(duration: Double = defaultFadeDurationSeconds,
velocity: Double = defaultVelocity, onFinished: ((Bool)->())? = nil) {
fade(
fromVolume: Double(player.volume), toVolume: 1,
duration: duration, velocity: velocity, onFinished: onFinished)
}
/**
Fade out the sound by gradually decreasing the volume.
- parameter duration: duration of the fade, in seconds. Default duration: 3 seconds.
- parameter velocity: a number specifying how fast the sound volume is changing. Velocity of 0 creates a linear fade. Values greater than zero produce more exponential fade affect. Exponential fade sounds more gradual to a human ear. The fade sounds most natural with velocity parameter from 2 to 5. Default value: 2.
- parameter onFinished: an optional closure that will be called after the fade has ended. The closure will be passed a boolean parameter `finished` indicating whether the fading has reached its end value (true) or if the fading has been cancelled (false).
*/
open func fadeOut(duration: Double = defaultFadeDurationSeconds,
velocity: Double = defaultVelocity, onFinished: ((Bool)->())? = nil) {
fade(
fromVolume: Double(player.volume), toVolume: 0,
duration: duration, velocity: velocity, onFinished: onFinished)
}
/**
Gradually change the volume of the sound.
- parameter fromVolume: the starting volume, a value from 0 to 1.
- parameter toVolume: the end volume that will be reached at the end of the fade, a value from 0 to 1.
- parameter duration: duration of the fade, in seconds. Default duration: 3 seconds.
- parameter velocity: a number specifying how fast the sound volume is changing. Velocity of 0 creates a linear fade. Values greater than zero produce more exponential fade affect. Exponential fade sounds more gradual to a human ear. Default value: 2. The fade sounds most natural with velocity parameter from 2 to 5.
- parameter onFinished: an optional closure that will be called after the fade has ended. The closure will be passed a boolean parameter `finished` indicating whether the fading has reached its end value (true) or if the fading has been cancelled (false).
*/
open func fade(fromVolume: Double, toVolume: Double,
duration: Double = defaultFadeDurationSeconds,
velocity: Double = defaultVelocity, onFinished: ((Bool)->())? = nil) {
self.fromVolume = Cephalopod.makeSureValueIsBetween0and1(value: fromVolume)
self.toVolume = Cephalopod.makeSureValueIsBetween0and1(value: toVolume)
self.fadeDurationSeconds = duration
self.fadeVelocity = velocity
callOnFinished(finished: false)
self.onFinished = onFinished
player.volume = Float(self.fromVolume)
if self.fromVolume == self.toVolume {
callOnFinished(finished: true)
return
}
startTimer()
}
/// Stop changing the volume. It does not stop the playback.
open func stop() {
callOnFinished(finished: false)
stopTimer()
}
private var fadeIn: Bool {
return fromVolume < toVolume
}
private func callOnFinished(finished: Bool) {
let saveOnFinished: ((Bool)->())? = onFinished
onFinished = nil // Make sure it is called only once
saveOnFinished?(finished)
}
private func startTimer() {
stopTimer()
currentStep = 0
let delay = 1 / volumeAlterationsPerSecond
timer = AutoCancellingTimer(interval: delay, repeats: true) { [weak self] in
self?.timerFired();
}
}
private func stopTimer() {
if let currentTimer = timer {
currentTimer.cancel()
timer = nil
}
}
func timerFired() {
if shouldStopTimer {
player.volume = Float(toVolume)
stopTimer()
callOnFinished(finished: true)
return
}
let currentTimeFrom0To1 = Cephalopod.timeFrom0To1(
currentStep: currentStep, fadeDurationSeconds: fadeDurationSeconds, volumeAlterationsPerSecond: volumeAlterationsPerSecond)
var volumeMultiplier: Double
var newVolume: Double = 0
if fadeIn {
volumeMultiplier = Cephalopod.fadeInVolumeMultiplier(timeFrom0To1: currentTimeFrom0To1,
velocity: fadeVelocity)
newVolume = fromVolume + (toVolume - fromVolume) * volumeMultiplier
} else {
volumeMultiplier = Cephalopod.fadeOutVolumeMultiplier(timeFrom0To1: currentTimeFrom0To1,
velocity: fadeVelocity)
newVolume = toVolume - (toVolume - fromVolume) * volumeMultiplier
}
player.volume = Float(newVolume)
currentStep += 1
}
var shouldStopTimer: Bool {
let totalSteps = fadeDurationSeconds * volumeAlterationsPerSecond
return Double(currentStep) > totalSteps
}
class func timeFrom0To1(currentStep: Int, fadeDurationSeconds: Double,
volumeAlterationsPerSecond: Double) -> Double {
let totalSteps = fadeDurationSeconds * volumeAlterationsPerSecond
var result = Double(currentStep) / totalSteps
result = makeSureValueIsBetween0and1(value: result)
return result
}
// Graph: https://www.desmos.com/calculator/wnstesdf0h
class func fadeOutVolumeMultiplier(timeFrom0To1: Double, velocity: Double) -> Double {
let time = makeSureValueIsBetween0and1(value: timeFrom0To1)
return pow(M_E, -velocity * time) * (1 - time)
}
class func fadeInVolumeMultiplier(timeFrom0To1: Double, velocity: Double) -> Double {
let time = makeSureValueIsBetween0and1(value: timeFrom0To1)
return pow(M_E, velocity * (time - 1)) * time
}
private class func makeSureValueIsBetween0and1(value: Double) -> Double {
if value < 0 { return 0 }
if value > 1 { return 1 }
return value
}
}