A sound fader for AVAudioPlayer written in Swift for iOS, tvOS and macOS.

Overview

Cephalopod, a sound fader for AvAudioPlayer written in Swift - iOS, tvOS and macOS

Carthage compatible CocoaPods Version License Platform

This library can help fading sounds in and out with AvAudioPlayer. One can set duration, velocity of the fade and a completion function. Velocity can vary from linear to exponential.

cephalopod = Cephalopod(player: player)
cephalopod?.fadeIn()

Juvenile cuttlefish camouflaged against the seafloor

Juvenile cuttlefish camouflaged against the seafloor. Photo taken by Raul654. Source: Wikimedia Commons.

Setup

There are three ways you can add Cephalopod to your Xcode project.

Add source (iOS 7+)

Simply add the CephalopodDistrib.swift file to your project.

Setup with Carthage (iOS 8+)

Alternatively, add github "evgenyneu/Cephalopod" ~> 4.0 to your Cartfile and run carthage update.

Setup with CocoaPods (iOS 8+)

If you are using CocoaPods add this text to your Podfile and run pod install.

use_frameworks!
target 'Your target name'
pod 'Cephalopod', '~> 4.0'

Legacy Swift versions

Setup a previous version of the library if you use an older version of Swift.

Usage

The following example shows how to play an mp3 file with a fade in effect.

import AVFoundation
import Cephalopod // For CocoaPods and Carthage
// ---

var playerInstance: AVAudioPlayer?
var cephalopod: Cephalopod?

override func viewDidLoad() {
  super.viewDidLoad()

  // Create a 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()
}

Fade in / fade out

cephalopod?.fadeIn()
cephalopod?.fadeOut()

// Supply fade duration and velocity, in seconds
cephalopod?.fadeIn(duration: 3, velocity: 2)
cephalopod?.fadeOut(duration: 3, velocity: 2)

// Supply finish closure
cephalopod?.fadeIn(duration: 3, velocity: 2) { finished in }
cephalopod?.fadeOut(duration: 3, velocity: 2)  { finished in }

Supply fade start/end volume and completion callback

cephalopod?.fade(fromVolume: 0.3, toVolume: 0.7, duration: 3, velocity: 2) { finished in
  print("Finished fading")
}

Arguments:

fromVolume - the start volume, a number between 0 and 1.

toVolume - the end volume, a number between 0 and 1.

duration - duration of the fade, in seconds. Default duration: 3 seconds.

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.

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).

Set the quality of fade

cephalopod?.volumeAlterationsPerSecond = 20

Larger numbers will produce finer fade effect at expense of CPU juice. Default value: 30.

Stop the volume change

One can cancel the ongoing volume change by calling the stop() method. Note that it stops changing the volume but does not stop the playback.

cephalopod?.stop()

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 exponential fade affect. Exponential 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

Cephalopod sound fader for iOS written in swift

Alternative solutions

Here is a list of other sound libraries for iOS.

Thanks 👍

  • nschucky for updating to Swift 2.2 selector syntax.

Credits

License

Cephalopod is released under the MIT License.

Feedback is welcome

If you notice any issue, got stuck or just want to chat feel free to create an issue. I will be happy to help you.

You might also like...
🅿️ PandoraPlayer is a lightweight music player for iOS, based on AudioKit and completely written in Swift.
🅿️ PandoraPlayer is a lightweight music player for iOS, based on AudioKit and completely written in Swift.

Made by Applikey Solutions Find this project on Dribbble Table of Contents Purpose Features Supported OS & SDK Versions Installation Usage Demo Releas

An original digital art work for macOS, iOS and web
An original digital art work for macOS, iOS and web

WordClock WordClock versions of various vintages, for various platforms. https://www.simonheys.com/wordclock/ Downloads Currently avaiaible to downloa

11t is an iOS and Android app for connecting to Mastodon, written in Flutter.

README 11t is an iOS and Android app for connecting to Mastodon, written in Flutter. I connect to Mastodon on mastodon.social, but everyone can start

Sentiments is an iOS app written in Swift that analyzes text for positive or negative sentiment
Sentiments is an iOS app written in Swift that analyzes text for positive or negative sentiment

Sentiments Sentiments is an iOS app written in Swift that analyzes text for positive or negative sentiment. Positive sentiment is highlighted in green

macOS app that allows the control of Spotify and AppleMusic/iTunes music playback from the menu bar.
macOS app that allows the control of Spotify and AppleMusic/iTunes music playback from the menu bar.

PlayStatus is a simple macOS app that allows the control of Spotify, Apple Music(macOS 10.15+) and iTunes including iTunes Radio/Beats1 playback from

Simple command line utility for switching audio inputs and outputs on macOS

Switch Audio Simple command line utility for switching audio inputs and outputs

A minimal chromatic tuner for iOS & macOS.
A minimal chromatic tuner for iOS & macOS.

Zen Tuner A minimal chromatic tuner. Works well with any instrument, whether it's woodwinds, brass, strings or voice. Dark Light Features Beautiful, c

MuVis is a macOS, iOS, iPadOS app for real-time music visualization.
MuVis is a macOS, iOS, iPadOS app for real-time music visualization.

MuVis MuVis is an open-source multiplatform app (using SwiftUI, Swift, and Xcode) for music visualization. It renders informative (and musically usefu

MuVis is a macOS, iOS, iPadOS app for real-time music visualization.
MuVis is a macOS, iOS, iPadOS app for real-time music visualization.

MuVis MuVis is an open-source multi-platform app (using SwiftUI, Swift, and Xcode) for music visualization. It renders informative (and musically usef

Comments
  • Integration with Objective C

    Integration with Objective C

    Hi

    Thanks for this wonderful library. I am trying to integrate this library in my project written in Objective C. I've successfully added the Swift code in my code but there's no impact on volume while trying different methods.

    //self.BackgroundMusicPlayer => Name of my AVAudioPlayer

    Cephalopod *cep = [[Cephalopod alloc] initWithPlayer:self.BackgroundMusicPlayer]; 1) [cep fadeFromVolume:0 toVolume:1 duration:5 velocity:1 onFinished:^(BOOL finished) { NSLog(@"Fading Done"); }];

    1.  [cep fadeInDuration:5 velocity:1 onFinished:^(BOOL finished) {
          NSLog(@"Fading Done");
       }];
      

    Any help in this regards will be highly appreciated.

    Thanks!

    opened by aareeph 8
  • Newbee questions

    Newbee questions

    Hello, and first of all contratulations for this amazing repo! I want to start an app I'm wondering a few aspects of it:

    • The app will stream audio from a server over the network. Can this library work with AVPlayer instead of AVAudioPlayer?
    • The way the app will be built, I will need to seek and crossfade through the audio file and crossfade between two different audio files. Is this possible with this library? My first idea was to create two instances of AVPlayer in order to crossfade them, is this a good method? If not, what do you recommend?

    I've been developing iOS apps for a few years but this is my first audio-related project and I'm a bit lost.

    Thanks guys!

    opened by JosepBernad 2
  • Fade out effect at the end of song

    Fade out effect at the end of song

    Is it possible to set a fade out event at the end of the song (without any additional times from my side)? For instance, I have a track (2:00 min) and I want to achieve a fade out effect during 10 second from 1:50 - 2:00.

    opened by Otbivnoe 1
  • Prevent fade from freezing with the main thread

    Prevent fade from freezing with the main thread

    Before this change the Timer would run on the main thread, meaning if your UI froze, so did the audio fade. Grand Central Dispatch allows it to run on a background thread as well run much more efficiently.

    This simply converts AutoCancellingTimerInstance to use DispatchQueue instead of Timer.

    opened by thecodewarrior 1
Owner
Evgenii Neumerzhitckii
🐋🦔🐢🐝wow
Evgenii Neumerzhitckii
Play and share sound inserts from Medo e Delírio em Brasília, a Brazilian podcast.

Play and share sound inserts from Medo e Delírio em Brasília, a Brazilian podcast.

Rafael Schmitt 18 Dec 26, 2022
iOS framework for the Quiet Modem (data over sound)

QuietModemKit This is the iOS framework for https://github.com/quiet/quiet With this library, you can send data through sound. Live demo: https://quie

Quiet Modem Project 442 Nov 17, 2022
PitchPerfect - A simple iOS app for the Udacity Nanodegree which explores AVFoundation to record a short sound

PitchPerfect App A simple iOS app for the Udacity Nanodegree which explores AVFo

Mark Han 0 Feb 12, 2022
AudioKit Sample Player (ROM Player) - EXS24, Sound Font, Wave Player

AudioKit ROM / Sample Player Welcome to the official AudioKit example of a sample-based music instrument written in Swift. It can be modified to play

AudioKit 500 Dec 27, 2022
OSCKit - The OSCKit package provides the classes needed for your apps to communicate among computers, sound synthesizers

OSCKit The OSCKit package provides the classes needed for your apps to communica

Sammy Smallman 23 Nov 27, 2022
AudioKit is an audio synthesis, processing, and analysis platform for iOS, macOS, and tvOS.

AudioKit is an audio synthesis, processing, and analysis platform for iOS, macOS (including Catalyst), and tvOS. Installation To add AudioKit

AudioKit 9.5k Dec 31, 2022
Swift audio synthesis, processing, & analysis platform for iOS, macOS and tvOS

AudioKit AudioKit is an audio synthesis, processing, and analysis platform for iOS, macOS (including Catalyst), and tvOS. Installation To add AudioKit

AudioKit 8.7k Sep 30, 2021
AudioPlayer is a simple class for playing audio in iOS, macOS and tvOS apps.

AudioPlayer AudioPlayer is a simple class for playing audio in iOS, macOS and tvOS apps.

Tom Baranes 260 Nov 27, 2022
Voice Memos is an audio recorder App for iPhone and iPad that covers some of the new technologies and APIs introduced in iOS 8 written in Swift.

VoiceMemos Voice Memos is a voice recorder App for iPhone and iPad that covers some of the new technologies and APIs introduced in iOS 8 written in Sw

Zhouqi Mo 322 Aug 4, 2022
An iOS and macOS audio visualization framework built upon Core Audio useful for anyone doing real-time, low-latency audio processing and visualizations.

A simple, intuitive audio framework for iOS and OSX. Deprecated EZAudio has recently been deprecated in favor of AudioKit. However, since some people

Syed Haris Ali 4.9k Jan 2, 2023