How To Add Background Music In Swift?

Adding music is a common request for mobile video games. When I built my first iOS game, I had to research this problem and find its solution.

How To Add Background Music In Swift With Code Examples

Create a class called MusicPlayer.swift.

import Foundation
import AVFoundation

class MusicPlayer {

}

Next, we’ll add a property that makes this a singleton class. A singleton class means there will be only one instance of this class. This prevents from double background music from playing which could result in a poor user experience.

import Foundation
import AVFoundation

class MusicPlayer {
    static let shared = MusicPlayer()
}

Then create a property called audioPlayer that is of type AVAudioPlayer. Also, create a function that is called startBackgroundMusic. AVAudioPlayer is a class that provides playback of audio data from a file or memory on iOS devices. Our file should now look like this:

import Foundation
import AVFoundation

class MusicPlayer {
    static let shared = MusicPlayer()
    var audioPlayer: AVAudioPlayer?

    func startBackgroundMusic() {

    }
}

Now we’ll need to fill in our function startBackgroundMusic(). Let’s load in the music file into an NSURL safely.

import Foundation
import AVFoundation

class MusicPlayer {
    static let shared = MusicPlayer()
    var audioPlayer: AVAudioPlayer?

    func startBackgroundMusic() {
        if let bundle = Bundle.main.path(forResource: "backgroundMusic", ofType: "mp3") {
            let backgroundMusic = NSURL(fileURLWithPath: bundle)
        }
    }
}

Load the backgroundMusic into our audioPlayer, set it to loop infinitely (-1 is used for infinite loops). Then we’ll prepareToPlay and finally play.

class MusicPlayer {
    static let shared = MusicPlayer()
    var audioPlayer: AVAudioPlayer?

    func startBackgroundMusic() {
        if let bundle = Bundle.main.path(forResource: "backgroundMusic", ofType: "mp3") {
            let backgroundMusic = NSURL(fileURLWithPath: bundle)
            do {
                audioPlayer = try AVAudioPlayer(contentsOf:backgroundMusic as URL)
                guard let audioPlayer = audioPlayer else { return }
                audioPlayer.numberOfLoops = -1
                audioPlayer.prepareToPlay()
                audioPlayer.play()
            } catch {
                print(error)
            }
        }
    }
}

You’ll notice we have safely wrapped everything into a do and catch block as there may be errors thrown when loading music into a AVAudioPlayer. We also safely unwrap audioPlayer with a guard statement before calling its functions.

After you’ve completed the singleton MusicPlayer class, you can now start the background music quite easily in any class. Simply call the singleton like so:

MusicPlayer.shared.startBackgroundMusic()

Your background music player is now complete. You may consider adding another option to stop the background music if you please. Simply add the following function to your MusicPlayer class

func stopBackgroundMusic() {
    guard let audioPlayer = audioPlayer else { return }
    audioPlayer.stop()
}

How about modifying the function to play a specific background song? We can use a parameter in startBackgroundMusic to do this. Our startBackgroundMusic function would then look like this:

func startBackgroundMusic(backgroundMusicFileName: String) {
    if let bundle = Bundle.main.path(forResource: backgroundMusicFileName, ofType: "mp3") {
        let backgroundMusic = NSURL(fileURLWithPath: bundle)
        do {
            audioPlayer = try AVAudioPlayer(contentsOf:backgroundMusic as URL)
            guard let audioPlayer = audioPlayer else { return }
            audioPlayer.numberOfLoops = -1
            audioPlayer.prepareToPlay()
            audioPlayer.play()
        } catch {
            print(error)
        }
    }
}

Where to find free music for iOS app

Music can complete an iOS app. This is especially true for video games or any app that has story telling involved. Music sets the right mood and emotions for the user. You must be careful when finding music online as most of it is copyright. Using copyright music without permission can lead to your iOS app being removed from the app store.

Here are some online resources where you can find free music for your iOS app:

Be sure to read the terms of the music that you are downloading. Some music requires attribution while others do not. If you unsure if the music you’ve found is free for commercial use, don’t use it. Getting flagged for copyright infringement will result in penalties by Apple. Don’t risk having your iOS becoming pulled from the app store.

You can also ask your favorite independent artists if you can use their music in your iOS app. Some may ask for a payment while others are happy to share their music. For larger artists, it can be more difficult to secure rights as multiple parties own rights to their music. This may include their record label and distribution channels.

How to add sound effects to iOS app

Sound effects can make a feel application feel more complete and add emphasis to certain user actions. It can be used to showcase certain gameplay elements or alert the user when an important action is taking place. Alerts are also a common use case for sound effects.

Adding sound effects to your app is very similar to adding background music. For most sound effects you don’t want to set it to loop. Here is an example implementation in Swift code:

func playSoundEffect(soundEffect: String) {
    if let bundle = Bundle.main.path(forResource: soundEffect, ofType: "mp3") {
        let soundEffectUrl = NSURL(fileURLWithPath: bundle)
        do {
            audioPlayer = try AVAudioPlayer(contentsOf:soundEffectUrl as URL)
            guard let audioPlayer = audioPlayer else { return }
            audioPlayer.play()
        } catch {
            print(error)
        }
    }
}

You can then call this function when a user clicks a button or performs another action.

How to play music from an iOS app in the background

If you’re creating a podcasting app or a music player iOS app, you’ll want to play music when your app is in the background. This is similar to how Spotify plays music even when your phones screen is off.

You’ll first have to enable background audio in your application’s project settings like so:

make_11

Next you’ll need to set the appropriate AVAudioSessionCategory. Here’s a table describing the different modes. The mode you pick will be different depending on your apps needs.

Category Silenced By Screen Locking Interrupts Input or Output
AVAudioSessionCategoryAmbient Yes No Out
AVAudioSessionCategorySoloAmbient Yes Yes Out
AVAudioSessionCategoryPlayback No Yes Out
AVAudioSessionCategoryRecord No Yes In
AVAudioSessionCategoryPlayAndRecord No Yes Both
AVAudioSessionCategoryMultiRoute No Yes Both

Once you’ve selected the right category and set it to your AVAudioPlayer, you can then call play just like the above examples.

Category Options

There are also additional category options that change the behavior of the sound coming from your app. These options include:

  • mixWithOthers
  • duckOthers
  • interruptSpokenAudioAndMixWithOthers
  • allowBluetooth
  • allowAirPlay
  • defaultToSpeaker

How to add music files to Xcode project

Adding music files such as mp3s or wavs is pretty simple in Xcode. Find the music file you’d like to add to your project in finder, then simply drag it into your Xcode application.

The file will then be available in your project navigator and you should be able to access throughout all your code. Be sure to type in only the file name as the extension goes into a different parameter for most method calls.

Where can I find musicians or composers for my iOS app? You can find musicians and composers for hire on freelance websites such as Upwork

Where can I buy music to use in my iOS app? You can buy music for your iOS app at Audio Jungle or Premium Beat.

Can I use copyrighted music in my iOS app? No, unless you have been given permission by the owners. You will be flagged by Apple and risk your app being removed from the app store.

If you liked this post and want to learn more, check out The Complete iOS Developer Bootcamp. Speed up your learning curve - hundreds of students have already joined. Thanks for reading!

Eddy Chung

I teach iOS development on ZeroToAppStore.com.

Similar Posts