简体   繁体   中英

Upon button press how can play a sound at EXACT same time as screen activity

I have a very specific issue and I have not yet found a solution. I have an IBAction for a button press. What I want to happen when this button is pressed is:

  1. play a sound file (this is about 5 seconds long sound)

  2. flash words on the screen (this is also about 5 seconds long)

I want this to happen concurrently so total time is about 5 seconds (words flashing while sound is playing).

What I end up with is that the words flash first, then the sound plays. I can never get them to go concurrently. Interestingly also I can never get the sound to play first even when placed at the very start of the action.

I've tried NSThread the sound, exec, CATransaction flush, but nothing can get them concurrent.

any ideas, btw I am total beginner programmer so sorry if not described the proper way.

-(IBAction) playButtonClick:(id)sender {
   int i;

    [_audioPlayer play];

    for (i=0; i<10; i++){
      [self.model getNextWord];   
      [self displayWord];
      [CATransaction flush];
      usleep(550000);   // word on screen for 0.55 seconds
    }

}

[CATransaction flush] is required else all I would see would be the very last word.

You have 2 tools at your disposal:

  • prepareToPlay()
  • playAtTime(_:)

Prepare so that the sound is in memory.

Calling this method preloads buffers and acquires the audio hardware needed for playback, which minimizes the lag between calling the play method and the start of sound output.

Wait until the rest of your UI is ready prior playing.

Use this method to precisely synchronize the playback of two or more AVAudioPlayer objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM