简体   繁体   中英

Pause button not working while toggling play/pause

Play Button is showing and when i hit play button it is playing audio file and turning the play button into pause button but when i hit pause button to pause it. It is not pausing but playing again the audiofile from the begining. After pause button is pressed not showing play button again

UIButton *playpauseButton = [UIButton buttonWithType:UIButtonTypeCustom];

[playpauseButton addTarget:self action:@selector(playpauseAction:) forControlEvents:UIControlEventTouchUpInside];

playpauseButton.frame = CGRectMake(0, 0, 50, 50);

[playpauseButton setImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal];

[playpauseButton setImage:[UIImage imageNamed:@"pause.png"] forState:UIControlStateSelected];

UIBarButtonItem *playpause = [[UIBarButtonItem alloc] initWithCustomView:playpauseButton];

-(void)playpauseAction:(id)sender 
{

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"theme" 
                                                     ofType:@"mp3"];

NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:filePath];

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

[fileURL release];

if  

  ([audioPlayer isPlaying]){

 [sender setImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal];

 [audioPlayer pause];

  } else {

 [sender setImage:[UIImage imageNamed:@"pause.png"] forState:UIControlStateNormal];

      [audioPlayer play];

  } 

}

How to make pause button work and show play button again once pause is pressed.

Thanks for help.

You are creating a new instance of AVAudioPlayer for each time you press the button. What you should do is work with a shared instance and save the pointer in audioPlayer.

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