使用相同按钮播放/暂停

时间:2012-12-17 08:23:38

标签: ios objective-c audio playback resume

如何使用相同的代码制作play/Pause按钮。

- (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"]; 
}

如何通过同一按钮恢复?

2 个答案:

答案 0 :(得分:7)

使用它来识别按钮状态:

在.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];
}

答案 1 :(得分:0)

创建一个布尔值,例如buttonIsPlayButton。如果按钮是播放按钮,则在开始时将其设置为true。然后按下按钮时,将其设置为false。每次按下按钮时,您都应该根据布尔值的值更改图像。