使用相同的按钮播放/暂停

时间:2022-07-07 19:45:25

How to make a play/Pause button with the same piece of code.

如何使用相同的代码制作播放/暂停按钮。

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

How can I resume by the same button?

如何通过相同的按钮恢复?

2 个解决方案

#1


7  

Use this to identify button state:

使用它来识别按钮状态:

In .h file make theAudio declaration :

在.h文件中制作音频声明:

AVAudioPlayer *theAudio;

In your method :

在你的方法中:

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

#2


0  

Create a boolean, such as buttonIsPlayButton. Set it to true at the start if the button is a play button. Then when the button is pressed, set it to false. You should have the image change each time the button is pressed based on the value of the boolean.

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

#1


7  

Use this to identify button state:

使用它来识别按钮状态:

In .h file make theAudio declaration :

在.h文件中制作音频声明:

AVAudioPlayer *theAudio;

In your method :

在你的方法中:

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

#2


0  

Create a boolean, such as buttonIsPlayButton. Set it to true at the start if the button is a play button. Then when the button is pressed, set it to false. You should have the image change each time the button is pressed based on the value of the boolean.

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