如何通过按一次 UIbutton
使用 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
变量的简单方法。
在viewDidLoad
中设置playing = 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;
}
}
关于iphone - 使用相同的按钮播放/暂停 [AVAudioPlayer],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6635604/