iPhone - 将按钮设置回初始状态

时间:2011-08-21 18:57:28

标签: iphone objective-c

我使用播放和停止图像创建了一个按钮,我想要的是当我按下播放并且声音结束时,停止图像应该返回播放,但是它不起作用,请有人帮忙。欢呼声。

- (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

1 个答案:

答案 0 :(得分:1)

确保将AVAudioPlayer实例的委托设置为self:

[audioPlayer setDelegate:self];

并在头文件中订阅AVAudioPlayerDelegate协议:

<AVAudioPlayerDelegate>

现在应该可以了。

编辑:这是订阅AVAudioPlayerDelegate协议的地方:

@interface _0_RabbanasViewController : UIViewController <AVAudioPlayerDelegate> {

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

希望现在有效。 :)

EDIT2:将audioPlayer委托设置为self:

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