切换播放/暂停不起作用

时间:2012-02-02 16:53:33

标签: iphone cocoa-touch avfoundation avaudioplayer

获取{[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]; ]

  }


}

我需要帮助修复此代码。

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

方法的整个播放/暂停部分完全无效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];
}

此外,您真的不需要在该方法中重新创建audioPlayer。把它放在-viewDidLoad或其他什么地方(通过“它”,我的意思是“第一行和'if'之间的所有方法)”。

答案 1 :(得分:0)

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

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,除非你检查它是否为零(第一次运行)。