切换 play/pause 按钮循环播放

Toggle play/pause button with loop playback

我有一个按钮,点击它可以在播放和暂停图像之间切换。当显示播放图像时,循环播放声音,当显示暂停图像时,声音停止播放。

我设法让它工作了,但有一个问题。当您点击按钮暂停(停止)时,它会最后一次播放声音(因此暂停操作会延迟声音的秒数)。

这是我的代码:

@implementation ViewController
AVAudioPlayer *myAudio;

- (void)viewDidLoad {
[super viewDidLoad];

[self.myButton setImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal];
[self.myButton setImage:[UIImage imageNamed:@"pause.png"] forState:UIControlStateSelected];
}

- (IBAction)buttonTapped:(id)sender {

NSURL *musicFile;
musicFile = [NSURL fileURLWithPath: [[NSBundle mainBundle] pathForResource:@"sound" ofType:@"mp3"]];
myAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:musicFile error:nil];


    if(self.myButton.selected)
        [self.myButton setSelected:NO];

    else
        [self.myButton setSelected:YES];

    if(self.myButton.selected)
        [myAudio setNumberOfLoops:-1];
        [myAudio play];
}

您所做的是在每次点击按钮时创建一个播放器。

您应该尝试创建一个 AVPlayer(在 viewDidLoad 中),并在 buttonTapped: 函数中使用它的 playpause 函数。

- (void)viewDidLoad {
  [super viewDidLoad];

  [self.myButton setImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal];
  [self.myButton setImage:[UIImage imageNamed:@"pause.png"] forState:UIControlStateSelected];

  NSURL *musicFile = [NSURL fileURLWithPath: [[NSBundle mainBundle]   pathForResource:@"sound" ofType:@"mp3"]];
  myAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:musicFile error:nil];
}

- (IBAction)buttonTapped:(id)sender {
  [self.myButton setSelected:!self.myButton.selected];
  if (self.myButton.selected) {
    [player seekToTime:kCMTimeZero];
    [player play];
  }
  else {
    [player pause];
  }
}

点击按钮将首先切换它的状态(选中或未选中),然后根据其状态,播放器将倒回并开始播放,或自行暂停(立即)。