Tutorial: Easy Audio Playback With AVAudioPlayer

By
On August 11, 2009

mobile application development

There are plenty of different places to get a mobile application designed. The problem is that they’re quite expensive. You might be able to figure out how to create your own, but it will probably look very basic. Instead, a good mobile application development software can make it even easier, so that you can build great looking apps all by yourself.

The Mobile design Starter Kit includes all the themes and scenarios you need to build whatever app you want. There are customizable and standard files that allow you to sell or offer anything you want through the kit. Everything is there, so once you spend the money, you can create as many mobile apps as you want – and even sell the apps if this is your thing.


The iPhone SDK’s AVFoundation framework includes AVAudioPlayer, an easy, feature rich, Objective-C based way of playing audio files.

This tutorial demonstrates how to use AVAudioPlayer. When you’ve finished the tutorial you’ll have created a simple app that plays an MP3 audio file in a loop when the app starts.

Source/Github

The code for this tutorial is available on GitHub. You can either clone the repository or download this zip.

Creating The Project

Launch Xcode and create a new View-Based iPhone application called AudioPlayer:

  1. Create a new project using File > New Project… from Xcode’s menu
  2. Select View-based Application from the iPhone OS > Application section, click Choose…
  3. Name the project as AudioPlayer and click Save

Adding The AVFoundation Framework

In order to use the SDK’s AVAudioPlayer class, we’ll need to add the AVFoundation framework to the project:

  1. Expand the Targets branch in the Groups & Files panel of the project
  2. Control-click or right-click the AudioPlayer item
  3. Choose Add > Existing Frameworks…
  4. Click the + button at the bottom left beneath Linked Libraries
  5. Choose AVFoundation.framework and click Add
  6. AVFoundation.framework will now be listed under Linked Libraries. Close the window

Next, we’ll import the AVFoundation headers in our view controller’s interface file and set up an AVAudioPlayer instance variable:

  1. Expand the AudioPlayer project branch in the Groups & Files panel of the project
  2. Expand the Classes folder
  3. Edit AudioPlayerViewController.h by selecting it
  4. Update the file. Changes are bold:

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>

@interface AudioPlayerViewController : UIViewController {
	AVAudioPlayer *audioPlayer;
}

@end

Adding An Audio File

We’ll need an audio file for playback. We’ll, unimaginatively, call the fille audiofile.mp3. Add it to the project:

  1. Control-click or right click on the Resources folder in the Groups & Files panel of the project
  2. Select Add > Existing Files… from the context menu
  3. Locate and select the file for import and click Add
  4. Check the Copy items into destination group’s folder (if needed) box and click Add

Starting Audio Playback

We’ll start the audio playback in ViewDidLoad:

  1. Uncomment the boilerplate ViewDidLoad method
  2. Update it as follows. Changes are bold:

- (void)viewDidLoad {
	[super viewDidLoad];

	NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/audiofile.mp3", [[NSBundle mainBundle] resourcePath]]];

	NSError *error;
	audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
	audioPlayer.numberOfLoops = -1;

	if (audioPlayer == nil)
		NSLog([error description]);
	else
		[audioPlayer play];

}

AVAudioPlayer is initialized with a URL, so we create one whose path points to the audio file in our on-the-phone resources directory. Setting the audio player’s numberOfLoops property to a negative number causes it to loop indefinitely. After configuring the player, we start the playback by sending the play message to the object.

Remember to release the audioPlayer in dealloc. Changes are bold:

- (void)dealloc {
	[audioPlayer release];
	[super dealloc];
}

More Capabilities

You can adjust the volume of the player, check/set the time played so far and pause or stop playback:

audioPlayer.volume = 0.5; // 0.0 - no volume; 1.0 full volume
NSLog(@"%f seconds played so far", audioPlayer.currentTime);
audioPlayer.currentTime = 10; // jump to the 10 second mark
[audioPlayer pause];
[audioPlayer stop]; // Does not reset currentTime; sending play resumes

Finally, you can implement the AVAudioPlayerDelegate protocol to, among other things, be notified when audio finishes playing — perhaps to move onto the next song in a playlist.

  • Gavin O’Brien

    Hi i was following your tutorial but at then end when i ran the project, no sound played. Is this a problem with my code or is it because i’m using the iPhone simulator?

  • Dan Grigsby

    Gavin: does it work when you download the zip? I run it on the sim without issue.

  • Gavin O’Brien

    Thanks for the reply i downloaded the zip and i had the URL to my soundfile wrong (a real facepalm moment).

    Great tutorial though it’s alot simpler to follow that some of the audio ones i’ve found.

  • http://www.xinsight.ca/ Jason

    The AVAudioPlayer is great, but watch out for some oddities when playing IMA4 files. There are some spurious calls to the delegate when you skip ahead or rewind in the file.

  • Pingback: ????? iPhone SDK: ????????????? ??????????????? ????? ? AVAudioPlayer | LookApp.ru - ?????? ???????? ? ??? ??? iPhone

  • Pingback: Tutorial: Easy Audio Playback With AVAudioPlayer | IPhoneMate

  • Pingback: Corporation Unknown » Happy Birthday

  • Pingback: Tutorial iPhone OS 3.0 . Partie 7 : Lecture audio avec AVAudioPlayer | Romain Boulay . Ingénieur développement informatique mobile

  • Patrick

    I noticed the sound only works if you create a View-based Application and not a Window-based Application. Is there any reason for this? Any solution? I need more than a single view…Any help would be appreciated! Thanks

  • David

    Instrument is saying that this program is leaking memory on play.

    I’ve also used Avaudioplayer on .wav files and it didn’t leak from those.

  • PinkertonWatts

    Great tutorial. Very simple and straightforward when compared to a lot of short sound tutorials online. Thanks so much!

  • http://davidmhoward.com David

    Hi

    I am looking for an example of using AVAudioPlayer with initWithData to load waveform data from memory. Can you help please (an email reply would be wonderful!)?

    Thanks

  • Sid

    Hello,

    Can we load the file from a remote location? e.g. http://somedomain.com/song.mp3?

    Thanks,
    Sid

  • Pingback: iPhoneGeek ???? » ??AVAudioPlayer????????

  • Momeks

    thank you . , i have some problem . when i tap the play button several times the music plays on and on … !! how can play music 1 time ? and about pause button , who works it ? sorry iam amateur

  • http://harish.jambhale@unnat-e.com Harish

    I followed the tutorial but no sound was played on the simulator.
    I downloaded the code for this tutorial but it also not being played.
    Strange thing is, it is not giving exception for either of the codes, but passes through the code without any show stopper.
    What could be the cause?

  • http://harish.jambhale@unnat-e.com Harish

    Strange !! its not working on the simulator but on the iphone
    but I have set the number of loops to 1 still its getting played twice. why so?

  • Jin

    Gosh, I have the opposite issue that others seem to have had. For me, it plays on the simulator but not on the iPhone (3.1.3).

  • Jin

    I’m pretty embarrassed to have to post this, but I had the silent mode switch on. At the same time, odd how that setting isn’t respected by the iPod app.

  • laurent

    thank you Dan, it’s perfect.