1

Basically in app have a play button for audio file, want to add another UIButton Besides Play button so that whenever it is pressed it will repeat audio file for some number of times or may be infinite until it is pressed again to stop repetition of playing audio file. How can this be achieved.

Below is the code for play/pause toggle button

_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;
    }
}
4

2 回答 2

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

}

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

于 2013-02-07T19:45:31.513 回答
0

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

于 2013-02-07T16:18:25.280 回答