Swift 2 examples – #7 Reproduce an audio file

This post is part of my collection: Swift 2 – For Beginners.

In this example we will see how to play and pause an audio file.

We can use the class AVAudioPlayer of AVFoundation to easily reproduce audio files, let’s start importing it.

import AVFoundation

We need the path to the audio file. E.g. To get a file named “allegro.mp3” in our project we can use the following line:

let audioPath = NSBundle.mainBundle().pathForResource("allegro", ofType: "mp3")!

That’s all, we are ready to create the AVAudioPlayer. The creation of the player could fail if for example the file would be corrupted. That’s why we need to create it in a “do try”:

do  {
   // Initialize the player with the audio file
   player = try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath))
           
   // Play
   player.play()
            
} catch{
   print("Error creating audio player.")
}

To pause the audio we just call:

player.pause()

Complete example:

import UIKit
// 1. Import audio video foundation
import AVFoundation

class ViewController: UIViewController {
    
    // 2. Create player
    var player = AVAudioPlayer()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 3. Get path to the audio file inside the application bundle
        let audioPath = NSBundle.mainBundle().pathForResource("allegro", ofType: "mp3")!
        
        do  {
            // 4. Initialize the player with the audio file inside a "do try cath"
            player = try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath))
            
            // 5. Play
            player.play()
        } catch{
            print("Error creating audio player.")
        }
    }
}

One thought on “Swift 2 examples – #7 Reproduce an audio file

Your feedback is important...

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s