2012-02-02 201 views
0

播放按鈕顯示,當我按下播放按鈕時,它正在播放音頻文件並將播放按鈕變成暫停按鈕,但是當我按暫停按鈕暫停時。它並沒有暫停,而是從開始時再播放音頻文件。暫停按鈕被按下不顯示播放按鈕後再次暫停按鈕在切換播放/暫停時不工作

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

您每次按下按鈕時都會創建一個AVAudioPlayer的新實例。你應該做的是使用共享實例並將指針保存在audioPlayer中。