我需要你的帮助。问题:有一个数组,其中对象4,当你按下播放声音时我有一个按钮并改变(+1)数组的索引=>当用户第二次点击时,声音应该以索引“2”等播放。问题是索引不会改变,并播放索引为“1”的文件。
*的·H
@interface AZViewController : UIViewController
{
NSInteger _acatindex;
}
@property (weak, nonatomic) NSMutableArray *acat;
- (IBAction)catbutt:(id)sender;
*的的.m
- (void)viewDidLoad
{
[super viewDidLoad];
//array
NSMutableArray *acat = [NSMutableArray arrayWithObjects:@"cat1", @"cat2", @"cat3", @"cat4", nil];
NSURL *url = [[NSBundle mainBundle] URLForResource:[acat objectAtIndex:_acatindex] withExtension:@"wav"];
NSAssert(url, @"URL is valid.");
NSError* error = nil;
self.catplayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
if(!self.catplayer)
{
NSLog(@"Error creating player: %@", error);
}
}
//button action
- (IBAction)catbutt:(id)sender
{
_acatindex++;
if (_acatindex == _acat.count)
{
_acatindex = 0;
}
AZTrace();
[self.catplayer stop];
[self stopTimer];
self.catplayer.currentTime = 0;
[self.catplayer prepareToPlay];
AZTrace();
[self.catplayer play];
self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES];
}
答案 0 :(得分:0)
您只能在-viewDidLoad:
方法中加载网址。您需要告诉音频播放器在-catbutt:
方法中播放数组中的下一个声音。您正在停止播放器,但在重新启动之前,您没有更改正在播放的文件。
答案 1 :(得分:0)
删除以下行:
[acat addObject:@"cat1"];
[acat addObject:@"cat2"];
[acat addObject:@"cat3"];
[acat addObject:@"cat4"];
声明您的数组和NSURL不在viewDidLoad中,请在.h中执行此操作:
@interface AZViewController : UIViewController
{
NSInteger _acatindex;
NSMutableArray *acat;
NSURL *url;
}
@property (weak, nonatomic) NSMutableArray *acat;
- (IBAction)catbutt:(id)sender;
现在从viewDidLoad()
:
url = [[NSBundle mainBundle] URLForResource:[acat objectAtIndex:_acatindex] withExtension:@"wav"];
NSAssert(url, @"URL is valid.");
NSError* error = nil;
self.catplayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
if(!self.catplayer)
{
NSLog(@"Error creating player: %@", error);
}
并将其粘贴到- (IBAction)catbutt:(id)sender
_acatindex++;
希望这会有所帮助。