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.") } } }
Pingback: Swift 2 examples – #8 Gestures Recognizers. Swipe, Tap, Rotate, Panning, etc. | Juan Carlos Sanchez's Blog