Reputation: 33
How to make a play/Pause
button with the same piece of code.
- (IBAction)min:(id)sender
{
NSString *path = [[NSBundle mainBundle] pathForResource:@"1min" ofType:@"mp3"];
AVAudioPlayer *theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
theAudio.delegate = self;
theAudio.numberOfLoops = -1;
[theAudio play];
[[NSUserDefaults standardUserDefaults] setObject:@"-" forKey:@"music"];
}
How can I resume by the same button?
Upvotes: 1
Views: 3891
Reputation: 3905
Use this to identify button state:
In .h file make theAudio
declaration :
AVAudioPlayer *theAudio;
In your method :
UIButton *button = (UIButton *)sender;
button.selected = !button.selected;
if(button.selected)
{
// Play
NSString *path = [[NSBundle mainBundle] pathForResource:@"1min" ofType:@"mp3"];
theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
theAudio.delegate = self;
theAudio.numberOfLoops = -1;
[theAudio play];
[[NSUserDefaults standardUserDefaults] setObject:@"-" forKey:@"music"];
}
else
{
// Pause
[theAudio pause];
}
Upvotes: 7
Reputation: 3108
Create a boolean, such as buttonIsPlayButton
. Set it to true at the start if the button is a play button. Then when the button is pressed, set it to false. You should have the image change each time the button is pressed based on the value of the boolean.
Upvotes: 0