我创建了一个图像数组并使用以下方法对其进行了动画处理:
imageview.animationImages = images;
imageview.animationDuration = 1;
imageview.animationRepeatCount = 1;
[imageview startAnimating];
这里imageview
是指向UIImageView对象的指针,images
是数组。我正在使用圆形矩形按钮来触发动画。当我在模拟器打开后第一次运行动画时...动画不会与声音同步,但是当我再次按下按钮使用它之后它就会发生。知道为什么吗?我正在使用系统声音API来播放短音。我为声音创建id
,然后使用以下方式播放:
AudioServicesPlaySystemSound(soundID);
我的猜测是,当我第一次触发动画时,模拟器需要一些时间来处理我正在使用的图像并构建数组。我总共使用了45张图片。因此,声音保持在动画图像之前。但是当我再次尝试时,图像已经被处理,因此动画和声音都是同步的。但这只是猜测。我不知道该怎么做。如果你想看看这里的整个代码,那就是:
-(IBAction)btnclicked:(id)sender {
NSMutableArray *images = [[NSMutableArray alloc]init]; //all alloc does is allocate memory. The -init method is crucial to actually initialize the object into a working state.
for (int imagenumber = 1; imagenumber <= 45; imagenumber++) {
NSMutableString *myString = [NSMutableString stringWithFormat:@"%i.png", imagenumber];
[images addObject:[UIImage imageNamed:myString]];
}
CGRect frame = CGRectMake(0.0, 0.0, 320, 460);
UIImageView *imageview = [[UIImageView alloc] initWithFrame:frame];
imageview.contentMode = UIViewContentModeScaleToFill;
imageview.animationImages = images;
imageview.animationDuration = 3.2;
imageview.animationRepeatCount = 1;
[imageview startAnimating];
[self.view addSubview:imageview];
AudioServicesDisposeSystemSoundID(soundID);
NSString *path = [[NSBundle mainBundle] pathForResource:@"giggity stick around" ofType:@"wav"];
NSURL *url = [NSURL fileURLWithPath:path];
AudioServicesCreateSystemSoundID((CFURLRef)url, &soundID);
AudioServicesPlaySystemSound(soundID);
[imageview release];
}
为了避免任何混淆......我的图像被命名为1.png,2.png等等,这就是我在构建数组时使用迭代的原因。
答案 0 :(得分:0)
最好的方法是创建一个播放声音的函数: - (void)playSound,然后在你的按钮动作中你应该写一个playSound函数的链接:[self playSound]。 这里很简单:
-(IBAction)XXX:(id)sender
{
//your imagesArray
[self playSound];
imageview.animationDuration = 1;
imageview.animationRepeatCount = 1;
[imageview startAnimating];
}
-(void)playSound
{
//yourcode for playing the sound
}
希望得到它的帮助。
编辑: 试试这个:
-(IBAction)btnclicked:(id)sender {
NSMutableArray *images = [[NSMutableArray alloc]init]; //all alloc does is allocate memory. The -init method is crucial to actually initialize the object into a working state.
for (int imagenumber = 1; imagenumber <= 45; imagenumber++) {
NSMutableString *myString = [NSMutableString stringWithFormat:@"%i.png", imagenumber];
[images addObject:[UIImage imageNamed:myString]];
}
CGRect frame = CGRectMake(0.0, 0.0, 320, 460);
UIImageView *imageview = [[UIImageView alloc] initWithFrame:frame];
imageview.contentMode = UIViewContentModeScaleToFill;
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/giggity stick around.wav", [[NSBundle mainBundle] resourcePath]]];
soundPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
soundPlayer.volume = 1;
[soundPlayer play];
imageview.animationImages = images;
imageview.animationDuration = 3.2;
imageview.animationRepeatCount = 1;
[imageview startAnimating];
[self.view addSubview:imageview];
}
我使用AVFoundation播放音频,请立即检查。