切换播放/暂停不起作用



{[audioPlayer pause];}Expected']'时收到红色警告,[[audioPlayer play];]Expected expression时收到另一条红色警告消息。

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:(UIButton *)sender
{   
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"theme" 
                                                     ofType:@"mp3"];
    NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:filePath];
    audioPlayer = [[AVAudioPlayer alloc] 
              initWithContentsOfURL:fileURL error:nil];
   [fileURL release];
   [audioPlayer prepareToPlay];
    audioPlayer.currentTime = 0;
    //[audioPlayer play];
     if  
  ([audioPlayer isPlaying]){
 Image:[UIImage imageNamed:@"play.png"] forState:UIControlStateSelected
 setImage:[UIImage imageNamed:@"pause.png"] forState:UIControlStateNormal
      {[audioPlayer pause];}
  } else {
setImage:[UIImage imageNamed:@"pause.png"] forState:UIControlStateSelected

Image:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal

      [[audioPlayer play]; ]
  }

}

我需要帮助修复此代码。

感谢您的帮助。

方法的整个播放/暂停部分在 Objective-C 中是完全无效的。试试这个:

if  ([audioPlayer isPlaying])
{
    [sender setImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal];
    [audioPlayer pause];
}
else
{
    [sender setImage:[UIImage imageNamed:@"pause.png"] forState:UIControlStateNormal];
    [audioPlayer play];
}

此外,您真的不需要以该方法重新创建音频播放器。把它(其中"它"的意思是"第一行和'if'之间的所有方法"(放在你的-viewDidLoad或其他东西中。

尝试设置委托并检查错误:

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"theme" ofType:@"mp3"];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: [NSURL fileURLWithPath:filePath] error:&err];
if( err ){
    NSLog(@"Failed with reason: %@", [err localizedDescription]);
} else{
    //set our delegate and begin playback
    audioPlayer.delegate = self;
    [audioPlayer play];
}

顺便说一句,您绝对不希望每次按下按钮时都分配 audioPlayer,除非您先检查它是否为 nil(第一次运行(。

最新更新