我有一个音板应用程序,可以播放声音并播放音乐,如果您单击按钮,它会暂停,但不会暂停,只会停止音乐。
音乐播放完毕后,按钮保持选中状态。
我的代码是;
- (IBAction)aint:(id)sender {
UIButton *aint = (UIButton *)sender;
aint.selected = !aint.selected;
if(aint.selected)
{
// Play
NSString *path2 = [[NSBundle mainBundle] pathForResource:@"2" ofType:@"mp3"];
theAudio2 = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path2] error:NULL];
theAudio2.delegate = self;
theAudio2.numberOfLoops = 0;
[theAudio2 play];
[[NSUserDefaults standardUserDefaults] setObject:@"-" forKey:@"music"];
}
else
{
// Pause
[theAudio2 pause];
}
}
我已经声明了Audio2和AVAudioPlayer。
最佳答案
试试这个,它将按预期工作-
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *path2 = [[NSBundle mainBundle] pathForResource:@"2" ofType:@"mp3"];
theAudio2 = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path2] error:NULL];
theAudio2.delegate = self;
theAudio2.numberOfLoops = 0;
}
- (IBAction)aint:(id)sender
{
UIButton *aint = (UIButton *)sender;
aint.selected = !aint.selected;
if(aint.selected)
{
// Play
[theAudio2 play];
[[NSUserDefaults standardUserDefaults] setObject:@"-" forKey:@"music"];
}
else
{
// Pause
[theAudio2 pause];
}
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
playerBtn.selected = NO;
}
关于ios - 播放和暂停功能,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20535921/