重复(循环)UIButton除了播放按钮

时间:2013-02-07 15:34:49

标签: iphone ios6 uibutton avaudioplayer

基本上在应用程序中有一个音频文件的播放按钮,想要添加另一个UIButton除了播放按钮,这样无论何时按下它都会重复音频文件若干次或者可能是无限的,直到再次按下它来停止重复播放音频文件。如何实现这一目标。

以下是播放/暂停切换按钮的代码

_playButton = [UIButton buttonWithType:UIButtonTypeCustom];
[_playButton addTarget:self action:@selector(playAction:) forControlEvents:UIControlEventTouchUpInside];
_playButton.frame = CGRectMake(80, 40, 25, 25);
[_playButton setImage:[UIImage imageNamed:@"1play.png"] forState:UIControlStateNormal];
[_playButton setImage:[UIImage imageNamed:@"audiopause.png"] forState:UIControlStateSelected];
UIBarButtonItem *play = [[UIBarButtonItem alloc] initWithCustomView:_playButton];

// Get the file path to the song to play.
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Theme"ofType:@"mp3"];

// Convert the file path to a URL.
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:filePath];

//Initialize the AVAudioPlayer.
player = [[AVAudioPlayer alloc]
          initWithContentsOfURL:fileURL error:nil];
player.delegate = self;

- (void)playAction:(id)sender
{
    if([player isPlaying])
    {
        [sender setImage:[UIImage imageNamed:@"1play.png"] forState:UIControlStateSelected];
        [player pause];
        //[timer invalidate];
        //timer = nil;
        //[self pauseTimer];
    }else{
        [sender setImage:[UIImage imageNamed:@"audiopause.png"] forState:UIControlStateNormal];
        [player play];
        slidertimer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(updateProgressBar:) userInfo:nil repeats:YES];
        [[NSRunLoop mainRunLoop] addTimer:slidertimer forMode:NSRunLoopCommonModes];
        timer = slidertimer;
    }
}

2 个答案:

答案 0 :(得分:0)

看起来你需要的是每x秒执行一次动作。您可以将UIButton正在执行的代码移动到某个方法,然后使用NSTimer循环执行该方法n次,然后在完成后使NSTimer无效。

答案 1 :(得分:0)

我终于像这样做了

 -(void) RepeatAction:(id)sender{

if (player && player.playing) {

    [player stop];

    player = nil;

    [_playButton setImage:[UIImage imageNamed:@"1play.png"] forState:UIControlStateNormal];

    return;
}

// Get the file path to the song to play.

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Theme"ofType:@"mp3"];

// Convert the file path to a URL.

NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:filePath];

//Initialize the AVAudioPlayer.

player = [[AVAudioPlayer alloc]
          initWithContentsOfURL:fileURL error:nil];

player.delegate = self;

    player.numberOfLoops = -1;

   [player play];

}

现在我唯一面临的问题是播放/暂停切换按钮受此干扰。如何解决这个问题。