播放和暂停功能

时间:2013-12-12 05:44:22

标签: ios media-player avaudioplayer

我有一个播放声音并应该播放音乐的音板应用程序,如果你点击按钮然后它会暂停但它不会暂停它只会停止音乐。 一旦音乐结束,按钮就会保持选中状态。

我的代码是;

 - (IBAction)aint:(id)sender {
UIButton *aint = (UIButton *)sender;

aint.selected = !aint.selected;

if(aint.selected)
{
    // Play
    NSString *path2 = [[NSBundle mainBundle] pathForResource:@"2" ofType:@"mp3"];
    theAudio2 = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path2] error:NULL];
    theAudio2.delegate = self;
    theAudio2.numberOfLoops = 0;
    [theAudio2 play];
    [[NSUserDefaults standardUserDefaults] setObject:@"-" forKey:@"music"];
}
else
{
    // Pause
    [theAudio2 pause];
 }
}

我宣布了音频2和AVAudioPlayer。

1 个答案:

答案 0 :(得分:1)

试试这个它会按预期工作 -

 - (void)viewDidLoad
    {
      [super viewDidLoad];

      NSString *path2 = [[NSBundle mainBundle] pathForResource:@"2" ofType:@"mp3"];
      theAudio2 = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path2] error:NULL];
      theAudio2.delegate = self;
      theAudio2.numberOfLoops = 0;
    }

 - (IBAction)aint:(id)sender 
    {
      UIButton *aint = (UIButton *)sender;
      aint.selected = !aint.selected;

      if(aint.selected)
      {
        // Play
        [theAudio2 play];
        [[NSUserDefaults standardUserDefaults] setObject:@"-" forKey:@"music"];
      }
      else
      {
        // Pause
        [theAudio2 pause];
      }
    }

 - (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
    {
       playerBtn.selected = NO;
    }
相关问题