除了播放按钮外,重复(循环)UIButton
Posted
技术标签:
【中文标题】除了播放按钮外,重复(循环)UIButton【英文标题】:Repeat (Loop) UIButton besides Play button 【发布时间】:2013-02-07 15:34:48 【问题描述】:基本上在应用程序中有一个音频文件的播放按钮,想要在播放按钮之外添加另一个 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;
【问题讨论】:
【参考方案1】:看起来您只需要每 x 秒执行一次操作。您可以将 UIButton 正在执行的代码移动到一个方法中,然后让 NSTimer 循环执行该方法 n 次,然后在完成后使 NSTimer 无效。
【讨论】:
我想为音频文件的重复按钮编写代码,以便当用户播放音频文件然后按下重复按钮以无限次或多次重复音频文件。如何为该重复按钮编码。【参考方案2】:我终于搞定了
-(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];
现在我面临的唯一问题是播放/暂停切换按钮受此干扰。如何解决这个问题。
【讨论】:
以上是关于除了播放按钮外,重复(循环)UIButton的主要内容,如果未能解决你的问题,请参考以下文章
“advanceToNextItem()”不允许循环播放所有视频