通过按一次UI按钮一次,可以通过IBAction播放声音,并使用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]; } }
解决方法
这是使用BOOL变量的简单方法.
在playDidLoad中设置播放= NO.
-(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; } }