使用相同按钮播放/暂停[AVAudioPlayer]

Alu*_*num 9 iphone xcode objective-c avaudioplayer

如何IBAction通过按一下来播放声音并UIbutton再次按下按钮暂停它AVAudioPlayer?此外,我想改变UIButton播放声音时的状态,以及声音播放时的状态.

这是我的代码:

- (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];
    }
}
Run Code Online (Sandbox Code Playgroud)

Spl*_*did 13

这是使用BOOLVariable 的简单方法.

设置playing = NOviewDidLoad.

-(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;
    }
}
Run Code Online (Sandbox Code Playgroud)