问题描述
- xcode中播放和暂停键
-
用代码实现一个播放/暂停键- (IBAction)min:(id)sender { NSString *path = [[NSBundle mainBundle] pathForResource:@"1min" ofType:@"mp3"]; AVAudioPlayer *theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL]; theAudio.delegate = self; theAudio.numberOfLoops = -1; [theAudio play]; [[NSUserDefaults standardUserDefaults] setObject:@"-" forKey:@"music"]; }
用同一个按钮。
解决方案
在.h 文件进行theAudio声明:
AVAudioPlayer *theAudio;
代码加入到方法中 :
UIButton *button = (UIButton *)sender;
button.selected = !button.selected;
if(button.selected)
{
// Play
NSString *path = [[NSBundle mainBundle] pathForResource:@"1min" ofType:@"mp3"];
theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
theAudio.delegate = self;
theAudio.numberOfLoops = -1;
[theAudio play];
[[NSUserDefaults standardUserDefaults] setObject:@"-" forKey:@"music"];
}
else
{
// Pause
[theAudio pause];
}
时间: 2024-10-30 05:15:32