views:

71

answers:

1

I'm using Page Control example from Apple. I've been able to play sound on the app itself using this code below but for some reasons, the sound went off early one page before it gets to the page where i set my sound to be played automatically.

- (void)viewDidLoad {
    pageNumberLabel.text = [NSString stringWithFormat:@"Page %d", pageNumber + 1];
    self.view.backgroundColor = [MyViewController pageControlColorWithIndex:pageNumber];

if (pageNumber == 3) {

     NSString *clapPath = [[NSBundle mainBundle] pathForResource:@"nearSound" ofType:@"caf"];
     CFURLRef clapURL = (CFURLRef ) [NSURL fileURLWithPath:clapPath];
     AudioServicesCreateSystemSoundID(clapURL, &testID);
     AudioServicesPlaySystemSound(testID);
}

So, supposedly when I scroll to page 4 (pageNumber == 3), the sound will be played but it got played on page 3 (pageNumber == 2), I wonder why is that?

If it can't be solved, I'll probably have to do the workaround then, put the sound before each page that I want to insert sound.

Also, How can I play the sound again when I scroll to that same page again? It seems that the sound get triggered only once after app launched.

I would very much appreciated any of your help.

A: 

You should cache the sound ID returned by the AudioServicesCreateSystemSoundID, and re-use that for whenever you need it.

Also, note that the viewDidLoad is only called when the view is loaded, not displayed. And load time may be called at a different time to display time. (It's quite possible that viewing page 2 causes an automatic load on page 3, hence triggering it again.)

Lastly, it's not good having page-display logic triggering the actions (like the sound). Instead, you should move it into the layer that actually does the page transition. That would solve your problem.

AlBlue
I see. That makes a lot of sense. Sorry for being such a noob, just wandering if you could me show what code should I use to cache the sound ID and where do you put sound actions then? Under AppDelegate.m? and which class?
viper15