2011-08-21 25 views
1

我創建了一個使用播放和停止圖像的按鈕,我想要的是當我按播放,聲音結束時,停止圖像應該回去播放,但它不工作,任何人都可以幫助這裏請。乾杯。iPhone - 設置按鈕回到初始狀態

- (IBAction)play { 

    if(clicked == 0){ 
     clicked = 1; 
     NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/TEST.wav", [[NSBundle mainBundle] resourcePath]]]; 

     NSError *error; 
     audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error]; 
     audioPlayer.numberOfLoops = 0; 


     [audioPlayer play]; 
     [start setImage:[UIImage imageNamed:@"stop.png"] forState:UIControlStateNormal]; 

    } 
    else{ 
     [audioPlayer release]; 
     clicked = 0; 
     [start setImage:[UIImage imageNamed:@"pla.png"] forState:UIControlStateNormal]; 
    } 

} 

//If user does not do anything by the end of the sound set the button to start 
- (void) audioPlayerDidFinishPlaying: (AVAudioPlayer *) player 
         successfully: (BOOL) flag { 
    if (flag==YES) { 
     [start setImage:[UIImage imageNamed:@"pla.png"] forState:UIControlStateNormal]; 
    } 
} 

這是我的.h文件

#import <UIKit/UIKit.h> 
#import <AVFoundation/AVFoundation.h> 

int clicked; 

@interface _0_RabbanasViewController : UIViewController { 

    IBOutlet UIScrollView *scroll; 
    AVAudioPlayer *audioPlayer; 
    IBOutlet UIButton *start; 

    IBOutlet UIImage *iPla; 
    IBOutlet UIImage *iStop; 
    BOOL successfully; 

} 

- (IBAction)play; 
- (IBAction)next; 

@end 
+0

並設置圖像 「pla.png」 手動工作(按下停機時) ? – fbrozovic

+0

是的,當我點擊播放時,音頻將播放,停止圖像將出現,當我點擊停止時,它將停止音頻並播放。我只是不知道要在什麼時候添加,到達最後,停止應該顯示。 – idipro

回答

1

確保您的AVAudioPlayer實例的委託設置爲self:

[audioPlayer setDelegate:self]; 

,並在頭文件,訂閱AVAudioPlayerDelegate協議:

<AVAudioPlayerDelegate> 

現在它應該工作。

編輯:在這裏訂閱AVAudioPlayerDelegate協議:

@interface _0_RabbanasViewController : UIViewController <AVAudioPlayerDelegate> { 

IBOutlet UIScrollView *scroll; 
AVAudioPlayer *audioPlayer; 
IBOutlet UIButton *start; 
... 

希望現在的工作。 :)

EDIT2:設置audioPlayer授人以自我位置:

audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error]; 
audioPlayer.numberOfLoops = 0; 
[audioPlayer setDelegate:self]; 
[audioPlayer play]; 

EDIT3:補充一點:

- (void) audioPlayerDidFinishPlaying: (AVAudioPlayer *) player 
         successfully: (BOOL) flag { 
    if (flag==YES) { 
     clicked = 0; 
     [start setImage:[UIImage imageNamed:@"pla.png"] forState:UIControlStateNormal]; 
    } 
} 
+0

感謝您的快速回答,我不明白您希望我放置代碼的位置,請介意將代碼添加到我發佈的代碼中。乾杯。 – idipro

+0

add [audioPlayer setDelegate:self];就在[audioPlayer播放]之前; ,你可以發佈你對應的.h文件,這樣我可以告訴你在哪裏放其他位? – fbrozovic

+0

+1,idipro必須檢查audioPlayerDidFinishPlaying是否被調用 –