Fade In and Fade Out Music iOS Tutorial

The AVAudioPlayer class can be used to Fade in and Out Music. In this tutorial a music track will be played, and the user can fade the music in or out using a switch, This tutorial is made with Xcode 10 and built for iOS 12.

Open Xcode and create a new Single View App.

For product name, use IOSFadeMusicTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.

For this project we need a music to play. Download the music file. Open the Assets Catalog and drag the file inside te catalog.

Go to the Storyboard and drag  a Label, a Switch and another Label to the top of the main View, positioning them next to each other. Select the left Label and give it a title of "Fade out". Select the right Label and give it a title of "Fade in". Hold the Ctrl key and select all three items. Go to the bottom-right of the Storyboard, click the "Embed in " button and select Stack View.

Select the Stack View and go to the Attributes inspector. In the Stack View section change the Distribution field to "Equal Spacing".

go to the bottom-right of the Storyboard and select the Resolve Auto-Layout button and select Reset to suggested Constraints.

The Storyboard will look like this.

Select the Assistant Editor and make sure the ViewController.swift is visible next to the Storyboard. Ctrl-drag or right-click-drag from the Button to the class and create the following Action.

Go to the ViewController.swift file and import the AVFoundation framework.

import AVFoundation

Add the following property

var player: AVAudioPlayer!

Change the viewDidLoad method to 

override func viewDidLoad() {
    guard let asset = NSDataAsset(name: "com-truise-cyanide-sisters") else { print("Error Loading Audio."); return }
    do {
        player = try AVAudioPlayer(data: asset.data)
    } catch { print("Error Playing Audio."); return }
    player.volume = 0
    player.numberOfLoops = -1

The music track will be played continuously by giving a value of -1  of the numberOfLoops property. The volume of the music track wil be silent at start.

Next, implement the fadeSwitchChanged(_:) action method

 @IBAction func fadeSwitchChanged(_ sender: UISwitch) {
    if sender.isOn {
        // Fading in
        player.setVolume(1, fadeDuration: 2)
    } else {
        // Fading out
        player.setVolume(0, fadeDuration: 2)

The start value of the switch will be On by default. In this case it is better to change the start value to Off, because the first switch change will be a fade in action. Go to the Storyboard, select the Switch and go to the Property inspector. Go to the Switch section and change the value to Off.

Build and Run the project, and change the switch to fade in or fade out the music

You can download the source code of the IOSFadeMusicTutorial at the ioscreator repository on github.