Last active
November 8, 2019 12:03
-
-
Save michaelevensen/daf72e5960c5d91770c771f5a3c94275 to your computer and use it in GitHub Desktop.
A simple fade-to function that employs a Timer for AVPlayer. Allows for specification of fade time rate / interval.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// Fades current player to specified `volume` with specified `duration`. | |
public func fadeTo(volume: Float, duration: TimeInterval = 5.0, completionHandler: @escaping () -> Void) { | |
// Current player | |
let player = self.currentPlayer | |
// Calculated increments for volume steps | |
let volumeIncrementationRate = 0.15 // Volume adjustments pr. seconds | |
let volumeDistance = player.volume - volume | |
let volumeSteps = duration / volumeIncrementationRate | |
let volumeDelta = abs(volumeDistance) / Float(volumeSteps) | |
// Stop periodic observer for current player (to avoid cross-fading) | |
self.removePeriodicTimeObserver(for: self.currentPlayer) | |
// Start timer | |
Timer.scheduledTimer(withTimeInterval: volumeIncrementationRate, repeats: true) { (timer) in | |
// Fade complete | |
func finish() { | |
completionHandler() | |
timer.invalidate() | |
} | |
// Negative volume adjustment | |
if player.volume > min(volume, player.volume) { | |
player.volume -= Float(volumeDelta) | |
if player.volume < volume { | |
finish() | |
} | |
} | |
// Positive volume adjustment | |
else { | |
player.volume += Float(volumeDelta) | |
if player.volume > volume { | |
finish() | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment