This is an iOS utility class that allows to fade sounds in and out with AvAudioPlayer
. One can set duration and velocity of the fade. Velocity can vary from linear to logarithmic.
Copy iiFaderForAvAudioPlayer.swift file to your project.
import AVFoundation
let soundURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(), "my_lovely_horse.mp3", nil, nil)
let player = AVAudioPlayer(contentsOfURL: soundURL, error: nil)
player.play()
player.volume = 0
let fader = iiFaderForAvAudioPlayer(player: player)
fader.fadeIn()
fader.fadeOut()
I would create a fader property somewhere in my app and keep a strong reference to the fader.
fader.fadeIn(duration: 3, velocity: 2)
fader.fade(fromVolume: 0.3, toVolume: 0.7, duration: 3, velocity: 2) { finished in
// fading finished
}
fader.volumeAlterationsPerSecond = 20
Larger numbers will produce finer fade effect at expense of CPU juice.
The following graph shows how sound volume changes during the fade.
Where x
is time and v
is velocity.
Velocity of 0 creates a linear fade. Values greater than zero produce more logarithmic fade affect. Logarithmic fade sounds more gradual to a human ear. I personally use velocity values from 2 to 5.
Live graph demo: https://www.desmos.com/calculator/wnstesdf0h
The lovely music was recorded by Carlos Vallejo and downloaded from http://www.flashkit.com/loops/Easy_Listening/Ill_Be_-Carlos_V-10012/index.php