user1120133
user1120133

Reputation: 3234

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.

Upvotes: 0

Views: 248

Answers (1)

Stavash
Stavash

Reputation: 14304

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.

Upvotes: 1

Related Questions