tags:

views:

215

answers:

3

I would like to play a sound for only a short span of time, shorter than the duration of the sound file. Therefore, at the same time as I start playing, I would like to queue up a task that will stop the sound.

I see two choices for queuing up the stop method: NSTimer and performSelector:withObject:afterDelay:

Does anyone know which of the two is most likely to trigger on time, or have a higher priority? It is not imperative that I get called with millisecond accuracy, but accuracy to 0.1 second would be great.


Addendum: Does anyone know where I could find documentation on the priority of different timer and delay tasks? For example, how would the below rank:

  • NSTimer tasks
  • performSelector
  • the calling of a view's drawRect after setNeedsDisplay has been called
  • the calling of a layer's drawing routines after setNeedsDisplay has been called
  • any other delayed tasks

And would it be useful to try to do this in a different thread?

A: 

From my understanding, they should be pretty much the same. However, the best way to figure this out is to test it yourself. Run a bunch of tests and record the exact time, then see which is closer.

jtbandes
I'm getting inconsistent results. Seems like depending on what I do in my runloop, then performSelector gets delayed. However, I am seeing random delays in NSTimer too. I'll keep at it.
mahboudz
My guess is that you're probably putting too much weight on this issue. It won't likely be much of a problem later on.
jtbandes
I'm not sure what you mean. The reason I want to stop the sound reliably is that the longer the sound plays, the more clues it provides to the player of my game. Being able to stop it on time is important.
mahboudz
+1  A: 

Have a NSTimer, but with a much smaller time interval than the one that your sound has to play. When your timer fires, and that is a couple of times while your sound plays, you would count how much time has passed since you started it. When that time exceeds a margin set by you, you stop the sound.

luvieere
+2  A: 

performSelector:withObject:afterDelay: will create a timer to know when to fire so both approaches should be equally (un-)reliable. If your code performs an expensive calculation on the main thread and doesn't return control to the run loop or if the run loop has to process lots of events, the timer won't fire on time.

Ole Begemann