Search code examples
iosnstimer

Play sounds after different time intervals


I want to use a speech synthesised sentence in an application demo. After pressing a button, a timer runs and after for example 12 seconds the first sentence is being spoken, then after 1.30min and so on.

The approach I was thinking of, is an NS Timer. But as far as I can see it only plays after a defined time. So do I need for any timespan a new timer? or can I track the time left and invoke a method call when a specific time is reached?

Thanks


Solution

  • I would do this using a dictionary with NSNumbers as the keys (representing seconds), and the sentence you want spoken as the value. Use a simple timer firing once every second, that updates an int, which (when converted to an NSNumber) would be checked against the dictionaries keys. I'm just logging in this example, but this should get you started,

    - (void)viewDidLoad {
        [super viewDidLoad];
        self.dict = @{@3:@"First", @5:@"second", @11:@"Third", @35:@"Fourth"};
        [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(doStuff:) userInfo:nil repeats:YES];
    }
    
    -(void)doStuff:(NSTimer *) aTimer {
        static int i = 0;
        i++;
        if ([self.dict.allKeys containsObject:@(i)]) {
            NSLog(@"%@", self.dict[@(i)]);
        }
    }