Search code examples
iphoneobjective-cxcodeavaudioplayer

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

Solution

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