开发者

iPhone - Set Button back to initial state

I created a button using a play and stop image, what I want is when i press play and that the sound finishes, the stop image should go back to play, but it's not working, can anyone help here please. cheers.

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

This is my .h file

#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 s开发者_Python百科uccessfully;

}

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

@end


Make sure you set the delegate of the AVAudioPlayer instance to self:

[audioPlayer setDelegate:self];

and in the header file, subscribe to the AVAudioPlayerDelegate protocol:

<AVAudioPlayerDelegate>

Now it should work.

EDIT: Here's where to subscribe to the AVAudioPlayerDelegate protocol:

@interface _0_RabbanasViewController : UIViewController <AVAudioPlayerDelegate> {

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

Hope it works now. :)

EDIT2: Set audioPlayer delegate to self here:

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

EDIT3: Add this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜