通过循环播放切换播放/暂停按钮

时间:2017-05-10 11:14:58

标签: ios objective-c avaudioplayer

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

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

这是我的代码:

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

1 个答案:

答案 0 :(得分:1)

您每次点击按钮时都在创建一个播放器。

您应该尝试创建一个AVPlayer(在viewDidLoad中),并在play函数中使用pausebuttonTapped:个函数。

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

点击按钮会首先切换它的状态(选择与否),然后根据其状态,播放器将倒带并开始播放,或暂停(立即)。

相关问题