开发者

UIImageView/AVAudioPlayer synchronization

开发者 https://www.devze.com 2023-03-09 13:35 出处:网络
I have an UIView that possess an UIImageView as a subview. This image view is intended to display an animation (basically, with the startAnimating method). When the animation start, I also need to pla

I have an UIView that possess an UIImageView as a subview. This image view is intended to display an animation (basically, with the startAnimating method). When the animation start, I also need to play a sound. For this purpose, I use AVAudioPlayer's prepareToPlay and play methods.

Problem I encounter is that the FIRST TIME the global animat开发者_开发问答ion (image animation itself + sound) is launched, the sound is systematically played before the image animation is actually started. Not weird at all considering there is no synchronisation whatsoever.

But how could this synchronization be achieved? Is there some sort of callback which could be used know when the image animation is playing and launch the sound play from there... Or maybe coupling UIImageView and AVAudioPlayer is not a good idea at all?

Here is my current implementation :

- (void)playSample {
    previewView_ = [[[PreviewView alloc] initWithFrame:topView.bounds
                                      backgroundImages:backgroundAnimationImages 
                                       characterImages:characterAnimationImages] autorelease];

    [previewView_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];


    [topView addSubview:previewView_];

    [audioPlayer_ setDelegate:self];
    [audioPlayer_ setVolume:1.0];   

    [previewView_ startPreview]; // This calls startAnimating on the UIImageView of previewView_
    [audioPlayer_ playSound];

}


Maybe you could use:

[audioPlayer playAtTime:[audioPlayer deviceCurrentTime] + someDelayTimeInterval]

I found the the audioPlayer (or prepareToPlay) was messing up with my display updates, so what I ended up doing was to create the audioPlayer for each sound in viewDidLoad: and play it in a method called in a background thread:

[self performSelectorInBackground:@selector(playAudioPlayer:)
withObject:self.audioPlayer];
0

精彩评论

暂无评论...
验证码 换一张
取 消