Chapter 12. Multimedia
12.0. Introduction
The Audio and Video (AV) Foundation framework in the iOS SDK allows developers to play and/or record audio and video with ease. In addition, the Media Player framework allows developers to play audio and video files.
Before you can run the code in this chapter, you must add the AVFoundation.framework and MediaPlayer.framework frameworks to your Xcode project. With the new LLVM compiler, the only thing you need to do to include these frameworks into your app is to import their umbrella header files like so:
import
AVFoundation
import
MediaPlayer
12.1. Playing Audio Files
Problem
You want to be able to play an audio file in your application.
Solution
Use the AV Foundation framework’s AVAudioPlayer
class.
Discussion
The AVAudioPlayer
class in the
AV Foundation framework can play back all audio formats supported by
iOS. The delegate
property of an
instance of AVAudioPlayer
allows you
to get notified by events, such as when the audio playback is
interrupted or when an error occurs as a result of
playing an audio file. Let’s have a look at a simple example that
demonstrates how we can play an audio file from the application’s
bundle:
import
UIKit
import
AVFoundation
class
ViewController
:
UIViewController
,
AVAudioPlayerDelegate
{
var
audioPlayer
:
AVAudioPlayer
?
/* The delegate message that will let us know that the player
has finished playing an audio file */
func
audioPlayerDidFinishPlaying
(
player
:
AVAudioPlayer
!
,
successfully
flag
:
Bool
)
{
println
(
"Finished ...
Get iOS 8 Swift Programming Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.