Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Maxence Roy
Maxence Roy
8,753 Points

How to play an audio file in iOS with Swift 3

Hi,

I'm working on an interval timer project.

Everything is working fine. Now, I want the app to play a MP3 file each time an interval is starting. I've installed the AudioToolbox.framework in the app but I need help with :

  • Where specifically do I add the audio files (I've got two 3s long mp3 files)
  • What's the code that I need to include to find the file, and trigger the sound
  • If possible, how do I make sure the sound is heard even when the app runs in background

Here's the function in which I'd include the timer trigger :

    /// Initiate the timer
    func runTimer() {
        timer = Timer.scheduledTimer(
            timeInterval: 1,
            target: self,
            selector: (#selector(ViewController.updateTimer)),
            userInfo: nil,
            repeats: true
        )

        isTimerRunning = true

        // Trigger MP3 file would go here
    }

Thanks!

  • Max

1 Answer

Maxence Roy
Maxence Roy
8,753 Points

Resolved!

First, I added the sound files to the main directory of the project (Alongside ViewController.swift).

/// Imported AVFoundation import AVFoundation

/// Added this variable var player: AVAudioPlayer?

/// Build this function
func playSound(name: String) {
    if let soundURL = Bundle.main.url(forResource: name, withExtension: "mp3") {

        do {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
            try AVAudioSession.sharedInstance().setActive(true)
            player = try AVAudioPlayer(contentsOf: soundURL)
            if let thePlayer = player {
                thePlayer.prepareToPlay()
                thePlayer.play()
            }
        }
        catch {
            print(error)
        }
    }
}

/// Called the function where needed, this would play GunShot.mp3 playSound(name: "GunShot")