The AVFoundation Framework in iOS can be used to play, edit and record audio and video. In this tutorial we will use the AVAudioPlayer object to play/pause/stop a mp3 file and also we will display the current time in the music track.
Open Xcode and create a new Single View Application. For product name, use playAudioDemo and then fill out the Organization Name, Company Identifier and Class Prefix fields with your customary values. Make sure only iPhone is selected in Devices, and that the Use Storyboards is deselected and Use Automatic Reference Counting checkbox is selected.
First we need to add the AVFoundation Framework to the projet. Go to the Project Summary -> Linked Frameworks and Libraries and add the AVFoundation Framework.
For this project we need the images for the play/pause and stop buttons and also the mp3 file. You can download them here. Extract this file and add the files to the project. Make sure you copy the items into the destination's folder.Note the mp3 file is a free downloaded file from the mp3.com site.
Let's setup the User Interface. Go to ViewController.xib and add 2 labels and 2 buttons to the view. Make the following changes in the Attributes Inspector.
- top Label: Center Alignment, Font - System 14.0
- center Label: Center Alignment. Font - System Bold 30.0
- left Button: Type -Custom, Image - play-and-pause-button.png
- right Button: Type - Custom, Image - stopbutton.png
The view should look like this.
In ViewController.h import the AVFoundation header file
Go the ViewController.m and add the following outlet properties and IBAction method definitions in the interface section.
@interface ViewController ()
@property (nonatomic, strong) IBOutlet UILabel *trackTitle;
@property (nonatomic, strong) IBOutlet UILabel *playedTime;
Go back to ViewController.xib and make the following connections.
- top label -> trackTitle outlet
- middle label -> playedTime outlet
- left button -> IBAction playOrPauseSound
- right button -> IBAction stopSound
Now the connections are made we can finish our code in ViewController.m. In the interface section add the following properties
@property (nonatomic, strong) AVAudioPlayer *audioPlayer;
@property (nonatomic) BOOL isPlaying;
@property (nonatomic, strong) NSTimer *timer;
The AVAudioPlayer class lets you play sound in any audio format available in iOS. With the isPlaying Boolean we'll determine if the music is currently playing. The NSTimer property is needed for displaying the current time in the music track.
Change the viewDidLoad method in
self.view.backgroundColor = [UIColor whiteColor];
self.isPlaying = NO;
self.trackTitle.text = @"The Stone Foxes - EveryBody Knows";
NSBundle *mainBundle = [NSBundle mainBundle];
NSString *filePath = [mainBundle pathForResource:@"thestonefoxes-everybodyknows" ofType:@"mp3"];
NSData *fileData = [NSData dataWithContentsOfFile:filePath];
NSError *error = nil;
self.audioPlayer = [[AVAudioPlayer alloc] initWithData:fileData error:&error]
The View's background is set to white, also the isPlaying property is set to NO. The mp3 file will be loaded in the fileData variable. Next, the AVAudioplayer is initialized with the filedata. The prepareToPlay method is used to preload the mp3 file into the buffer.
Next, implement the playOrPauseSound method
// Music is currently playing
self.isPlaying = NO;
// Music is currenty paused/stopped
self.isPlaying = YES;
self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTime) userInfo:nil repeats:YES];
First we check if the track is currently playing. If it is, we pause the track and change the isPlaying property. If the track isn't playing, we play it and change the isPlaying property. Then we'll create a NSTimer object, which will call the updateTime method every second. Let's implement this method.
NSTimeInterval currentTime = self.audioPlayer.currentTime;
NSInteger minutes = floor(currentTime/60);
NSInteger seconds = trunc(currentTime - minutes * 60);
// update your UI with currentTime;
self.playedTime.text = [NSString stringWithFormat:@"%d:%02d", minutes, seconds];
the currenttime property of audioplayer will be split up in minutes and seconds, which will be displayed to our playedTime property.
Finally implement the stopSound method.
self.audioPlayer.currentTime = 0;
self.isPlaying = NO;
The audioplayer calls the stop method and the currentTime is reset, so the next time when the play button is pressed, it will be played from the start. The isPlaying property is set to NO. Build and Run, press the play/pause and stop button to hear the sound.
You can download the source code of the playAudioDemo at the ioscreator repository on github.