我想从didSelectRowAtIndexPath实例中的UITableView项控制AVAudioPlayer的实例。
首次触摸行项会触发AVAudioPlayer的“播放”。第二次触摸行项会触发AVAudioPlayer的“停止”。
我可以让'游戏'工作,但不能让'停止'工作。此外,行项的后续触摸会在后台启动另一个音频线程。
代码示例 - 此方法准备使用音频文件和AVAudioPlayer:
- (void)makeReadyAudio {
NSString *path = [[NSBundle mainBundle] pathForResource:@"Murderers" ofType:@"mp3"];
NSURL *url = [NSURL fileURLWithPath:path];
NSError *error;
musicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
[musicPlayer prepareToPlay];
}
此块将启动&在didSelectRowAtIndexPath部分的case语句中停止AVAudioPlayer:
case 7: {
//touch to start audio sound playing, touch again to stop playing
[self makeReadyAudio];
if ([musicPlayer isPlaying]) {
[musicPlayer stop];
NSLog(@"musicPlayer tested to be playing, so stop it.");
} else {
[musicPlayer play];
NSLog(@"musicPlayer tested to be *not* playing, so play it.");
}
break;
}
答案 0 :(得分:1)
怎么样:
- (void) didSelectRowAtIndexPath:
{
if (player.isPlaying) {
[player stop];
} else {
[player start];
}
}
换句话说,让玩家保持身边,看看它在做什么。
答案 1 :(得分:0)
问题是,每次点击行都会调用makeReadyAudio
。你需要检查一下你是否已经这样做了。例如,通过执行以下操作:
if (musicPlayer == nil) {
[self makeReadyAudio];
}