Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play/Pause with the same button [AVAudioPlayer]

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];
    }
}
like image 428
Aluminum Avatar asked Jul 09 '11 15:07

Aluminum


1 Answers

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;
    }
}
like image 174
Splendid Avatar answered Oct 11 '22 23:10

Splendid