简体   繁体   中英

AVAudioPlayer - Pause button

My previous code was

- (void) playaudio: (id) sender
{
   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;
   [self.audioPlayer play];
}

- (void)pause: (id)sender

{
   [audioPlayer pause]; 

}

- (void)stop: (id)sender

{

  [audioPlayer stop];

 }

In the above code pause button was acting as stop button rather than pause where it was supposed to resume the audio file.

Now i have added simple statements to my code it is working to some extent but still not upto my expectations.

What happening now is when you play audio file and click on pause button nothing happens but when you click on the stop button it stops playing audio file and then when you press the pause button it resumes the audio file from where it was stopped by pressing stop button. Why is that when you press stop buttons only then pause button functions but not before that. I don't get this why?

Any ideas why this is happening

- (void)pause: (id)sender

{

  [audioPlayer pause];    
  [audioPlayer prepareToPlay];
  [audioPlayer play];


}


- (void) stop: (id) sender

{
    [audioPlayer stop];

 }

If anyone have any ideas that why this is happening. Will appreciate help.

Thanks in advance.

You shouldn't be recreating the audio file every time you play it. Here is how you could do this:

- (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];

 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM