2012-02-02 131 views
1

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

    } 


} 

我需要解決這個代碼的幫助。

感謝您的幫助。

回答

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之類的地方(用「it」表示「在第一行和'if'之間的那種方法」)。

+0

現在播放按鈕顯示,當我點擊播放按鈕時,它正在播放音頻文件,並將播放按鈕變成暫停按鈕,但當我點擊暫停按鈕來暫停它。它不是暫停,而是從開始播放音頻文件 – user1120133 2012-02-02 18:27:51

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

順便說一句,你絕對不希望每次按下按鈕時allocing的audioPlayer,除非你檢查它是否是零第一(爲首先通過)。

相關問題