Sie sind auf Seite 1von 2

Playing Audio in iPad:

1. Add AVFoundation.framework and AudioToolbox.framework

2. Open the ViewController.h file, we have added in this


file AVAudioPlayerDelegate protocol. They allow a delegate to respond
to audio interruptions , to audio decoding errors , and to the
completion of a sound’s playback. Added SystemSoundID for playing
sound, AVAudioPlayer for playing song, UIButton for display the button
and mention two IBAction. So make the following changes in the file.

#import <UIKit/UIKit.h>
#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>
@interface MusicPlayiPadViewController : UIViewController
<AVAudioPlayerDelegate> { SystemSoundID systemSoundID;
AVAudioPlayer *player; UIButton *StartStopSound;}

@property (nonatomic, retain) IBOutlet AVAudioPlayer *player; @property


(nonatomic, retain) IBOutlet UIButton *StartStopSound;

- (IBAction) playSound: (id) sender; - (IBAction) playSong: (id) sender;

3. Double click the ViewController.xib file and open it to the Interface


Builder. Open the view window and first drag two Round Rect from the
library and place it to the view window change the Round Rect name
into “Play Sound” and “PlaySong”. Next connect File’s Owner icon to
the view icon and select view. Select the Play Sound button from view
window and bring up connection inspector, next drag from the
TouchUpInside to the File’s Owner icon and select playSound: action.
Do it once more time for Play Song button and select playSong: action
and drag from the File’s Owner icon to the Play Sound button and
select StartStopSound. Done all connection, now save NIB file, close it
and go back to the Xcode.

4. Open the ViewController.m file and make the following changes:

- (void)viewDidLoad {
- (void)viewDidLoad {
NSLog(@"InView did load");
AudioServicesCreateSystemSoundID((CFURLRef)[NSURL
fileURLWithPath:[[NSBundle mainBundle] pathForResource: @"sound"
ofType:@"aif"]], &systemSoundID);
player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL
fileURLWithPath: [[NSBundle mainBundle] pathForResource:@"music"
ofType:@"mp3"]] error:nil];

[player prepareToPlay];

-(IBAction) playSound:(id) sender {


AudioServicesPlaySystemSound(systemSoundID);}

-(IBAction) playSong:(id) sender { if ([[NSString


stringWithFormat:@"%@", [StartStopSound
titleForState:UIControlStateNormal]] isEqualToString:@"Play Song"]) {
[player play]; [StartStopSound setTitle:@"Stop Song"
forState:UIControlStateNormal]; }else { [player stop];
[StartStopSound setTitle:@"Play Song"
forState:UIControlStateNormal]; }}

Das könnte Ihnen auch gefallen