How can I play a sound with an IBAction
by pressing on a UIbutton
once and pause it by pressing the button again using AVAudioPlayer
? Also I want to change the state of that UIButton
when the sound is playing and when it's not.
Here's my code:
- (IBAction)Beat
{
if ([Media2 isPlaying])
{
[Media2 pause];
[Button17 setSelected:NO];
}
else
{
Path = [[NSBundle mainBundle] pathForResource:@"Beat" ofType:@"mp3"];
AVAudioPlayer *Media2 = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:Path] error:NULL];
[Media2 setDelegate:self];
[Media2 play];
[Button17 setSelected:YES];
}
}
Here's is simple method using BOOL
Variable.
Set playing = NO
in viewDidLoad
.
-(void)PlayStop{
if (playing==NO) {
// Init audio with playback capability
[play setBackgroundImage:[UIImage imageNamed:@"hmpause.png"] forState:UIControlStateNormal];
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:______ error:&err];
[audioPlayer prepareToPlay];
audioPlayer.delegate=self;
[audioPlayer play];
playing=YES;
}
else if(playing==YES){
[play setBackgroundImage:[UIImage imageNamed:@"Audioplay.png"] forState:UIControlStateNormal];
[audioPlayer pause];
playing=NO;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With