首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >切换播放/暂停按钮,循环播放

切换播放/暂停按钮,循环播放
EN

Stack Overflow用户
提问于 2017-05-10 11:14:58
回答 1查看 166关注 0票数 0

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

我必须设法让它发挥作用,但有一个问题。当你点击按钮暂停(停止),它播放声音最后一次(因此暂停行动被延迟的秒数的声音)。

这是我的密码:

代码语言:javascript
复制
@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];
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-05-10 11:36:15

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

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

代码语言:javascript
复制
- (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];
  }
}

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43890868

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档