Play a audio file in Iphone

These are the codes for the Play, Pause, Stop, Resume button for playing a song. appSoundPlayer is a property of AVAudioPlayer declared in h file. Also this example plays a song in the resource folder.

#pragma mark -
   
#pragma mark *play*
   
- (IBAction) playaction {

       
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"songname" ofType:@"mp3"];
        NSURL
*newURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
       
self.soundFileURL = newURL;
       
[newURL release];
       
[[AVAudioSession sharedInstance] setDelegate: self];
       
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryAmbient error: nil];

   
// Registers the audio route change listener callback function
   
AudioSessionAddPropertyListener (
                                     kAudioSessionProperty_AudioRouteChange
,
                                     audioRouteChangeListenerCallback
,
                                     
self
                                     
);

   
// Activates the audio session.

   
NSError *activationError = nil;
   
[[AVAudioSession sharedInstance] setActive: YES error: &activationError];

   
AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: soundFileURL error: nil];
   
self.appSoundPlayer = newPlayer;
   
[newPlayer release];
   
[appSoundPlayer prepareToPlay];
   
[appSoundPlayer setVolume: 1.0];
   
[appSoundPlayer setDelegate: self];
   
[appSoundPlayer play];


   
[stopbutton setEnabled:YES];
   
[playbutton setEnabled: NO];
    playbutton
.hidden=YES;
    pausebutton
.hidden =NO;
}//playbutton touch up inside
#pragma mark -
#pragma mark *pause*
-(IBAction)pauseaction {
   
[appSoundPlayer pause];
    pausebutton
.hidden = YES;
    resumebutton
.hidden = NO;
}//pausebutton touch up inside
#pragma mark -
#pragma mark *resume*
-(IBAction)resumeaction{
   
[appSoundPlayer prepareToPlay];
   
[appSoundPlayer setVolume:1.0];
   
[appSoundPlayer setDelegate: self];
   
[appSoundPlayer play];
    playbutton
.hidden=YES;
    resumebutton
.hidden =YES;
    pausebutton
.hidden = NO;
}//resumebutton touch up inside
#pragma mark -
#pragma mark *stop*
-(IBAction)stopaction{

   
[appSoundPlayer stop];
   
[playbutton setEnabled:YES];
   
[stopbutton setEnabled:NO];
    playbutton
.hidden=NO;
    resumebutton
.hidden =YES;
    pausebutton
.hidden = YES;
}//stopbutton touch up inside

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>