Sunday, 3 July 2011

How to play sound in iPhone application?

This post deals with playing sound in iPhone applications. You can play sounds in your application using an instance of AVAudioPlayer class. AVAudioPlayer lets you play audio in different formats available in iOS. You can play, pause or stop an audio player using its properties.

1) Add the framework AVFoundation.framework from existing framework.

2) Lets say we have a view controller class “PlayViewController” . In .h file write the following code as shown below.

#import <UIKit/UIKit.h>
#import <AVFoundation/AVAudioPlayer.h>
@interface PlayViewController : UIViewController<avaudioplayerdelegate> {
AVAudioPlayer *player;
IBOutlet UIButton *button;
}

-(IBAction)play;
@end

3) In the above code we have imported “AVAudioPlayer.h” which is inside AVFoundation framework. We have also implemented AVAudioPlayerDelegate protocol in this class.

4) Now come to .m file and write the following code in “viewDidLoad” method.

NSString *soundFilePath = [[NSBundle mainBundle] pathForResource: @"snd1" ofType: @"mp3"];
NSURL *fileurl = [[NSURL alloc] initFileURLWithPath: soundFilePath];
player =[[AVAudioPlayer alloc] initWithContentsOfURL: fileurl error: nil];
[fileurl release];
[player prepareToPlay];
[player setDelegate: self];

Here snd1 is the name of the mp3 file present in the resources folder of the Xcode project.

5) Implement the play method as shown below.

-(IBAction)play
{
if (player.playing) {
[button setTitle: @"Play" forState: UIControlStateHighlighted];
[button setTitle: @"Play" forState: UIControlStateNormal];
[player pause];
}
else {
[button setTitle: @"Pause" forState: UIControlStateHighlighted];
[button setTitle: @"Pause" forState: UIControlStateNormal];
[player play];
}
}

Here property playing of player tells whether the player is currently playing or not, based on which we set the title for button.

6) Implement the following delegate method, as shown, in .m file

- (void) audioPlayerDidFinishPlaying: (AVAudioPlayer *) player successfully: (BOOL) completed {
if (completed == YES) {
[button setTitle: @"Play" forState: UIControlStateNormal];
}
}

This delegate method is called when the player is finished playing. We can change title of the button inside the implementaion of the above method.

7) Now open .xib file, add a UIButton and make connections as shown below.


8) Save, build and run your application.

No comments:

Post a Comment