Skip to content

carabina/sound-fader-ios

 
 

Repository files navigation

iOS sound fader for AvAudioPlayer written in Swift

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.

Installation

Copy iiFaderForAvAudioPlayer.swift file to your project.

Usage

Play an audio file

import AVFoundation

let soundURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(), "my_lovely_horse.mp3", nil, nil)
let player = AVAudioPlayer(contentsOfURL: soundURL, error: nil)
player.play()
player.volume = 0

Instantiate a fader

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.

Set fade duration and velocity

fader.fadeIn(duration: 3, velocity: 2)

Supply fade start/end volume, completion callback

fader.fade(fromVolume: 0.3, toVolume: 0.7, duration: 3, velocity: 2) { finished in
  // fading finished
}

Set the quality of fade

fader.volumeAlterationsPerSecond = 20

Larger numbers will produce finer fade effect at expense of CPU juice.

Volume functions

The following graph shows how sound volume changes during the fade.

Sound fade logarithmic velocity function for iOS/Swift

Fade in formula

Sound fade out logarithmic formula

Fade out formula

Sound fade in logarithmic formula

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

Demo app

Sound fader for iOS written in swift

Attribution

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

Project home

https://github.com/evgenyneu/sound-fader-ios

About

A sound fader for AVAudioPlayer written in Swift.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Swift 100.0%