切换播放/暂停时暂停按钮不起作用

时间:2012-02-02 19:48:03

标签: iphone

播放按钮正在显示,当我按下播放按钮时,它正在播放音频文件并将播放按钮变为暂停按钮,但是当我按下暂停按钮暂停播放按钮时。这不是暂停,而是从一开始就再次播放音频。按下暂停按钮后不再显示播放按钮

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

  } 

}

暂停按钮后如何使暂停按钮工作并再次显示播放按钮。

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

每次按下按钮,都会创建AVAudioPlayer的新实例。你应该做的是使用共享实例并将指针保存在audioPlayer中。