Chapter 8. Audio and Video

8.0. Introduction

The AV Foundation framework on 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. You can do this by following these steps:

  1. In Xcode, find your target.

  2. Right-click on the target and choose AddExisting Frameworks.

  3. Hold down the Command key and choose AVFoundation.framework and MediaPlayer.framework from the list.

  4. Select Add.

8.1. Playing Audio Files

Problem

You want to be able to play an audio file in your application.

Solution

Use the AV Foundation (Audio and Video 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 whenever the audio playback is interrupted or if 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 that is in our application’s bundle:

- (void) startPlayingAudio{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSBundle *mainBundle = [NSBundle mainBundle]; NSString *filePath = [mainBundle pathForResource:@"MySong" ofType:@"mp3"]; NSData *fileData = [NSData dataWithContentsOfFile:filePath]; ...

Get iOS 4 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.