Thursday, June 6, 2013

AVAudioPlayer stop example in Objective C (iOS).


AVAudioPlayer stop

Stops playback and undoes the setup needed for playback.

- (void)stop

Discussion of [AVAudioPlayer stop]
Calling this method, or allowing a sound to finish playing, undoes the setup performed upon calling the play or prepareToPlay methods.

The stop method does not reset the value of the currentTime property to 0. In other words, if you call stop during playback and then call play, playback resumes at the point where it left off.

AVAudioPlayer stop example.
Add a field to your view controller class:

@private AVAudioPlayer *currentAudio;
And then in this method, make the following changes:

if (currentAudio) {
    [currentAudio stop];
    [currentAudio release];
    currentAudio = nil;
} else {
    // what you already have goes here
}

Example of [AVAudioPlayer stop].
- (IBAction)buttonClicked
{
 if([audioPlayer isPlaying])
 {
  [audioPlayer stop];
  [audioPlayer release];
  audioPlayer = nil;
  audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfUrl:songUrl];
  [audioPlayer play];
}
// Do something like change view etc.
}

AVAudioPlayer stop example.
- (void) playaudio: (id) sender
{
   if(self.audioPlayer == nil) {
      NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Theme"
                                                 ofType:@"mp3"]; 
      NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:filePath]; 

      self.audioPlayer = [[AVAudioPlayer alloc]
                initWithContentsOfURL:fileURL error:nil];

      self.audioPlayer.currentTime = 0; //this could be outside the if if you want it to start over when they hit play
   }
   [self.audioPlayer play];
}

- (void)pause: (id)sender

{
   if([audioPlayer isPlaying]){
       [audioPlayer pause];
   } else {
       [audioPlayer play];
   }

}

- (void)stop: (id)sender

{

  [audioPlayer stop];

 }

End of AVAudioPlayer stop example article.