I am trying to start playing sound from a background task using the created AVAudioPlayer, so here is what I have.
For readability, I cut out all user-selected values.
- (void)restartHandler { bg = 0; bg = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{ [[UIApplication sharedApplication] endBackgroundTask:bg]; }]; tim = [NSTimer timerWithTimeInterval:.1 target:self selector:@selector(upd) userInfo:nil repeats:YES]; [[NSRunLoop currentRunLoop] addTimer:tim forMode:NSRunLoopCommonModes]; } - (void)upd { if ([[NSDate date] timeIntervalSinceDate:startDate] >= difference) { [self playSoundFile]; [tim invalidate]; [[UIApplication sharedApplication] endBackgroundTask:bg]; } } - (void)playSoundFile { NSError *sessionError = nil; [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&sessionError];
Explanation: bg , tim , startDate , difference and _player are globally declared variables. I call - (void)restartHandler from the user method and inside it starts a 10 Hz re-timer for - (void)upd . When a predetermined difference - (void)playSoundFile reached, - (void)playSoundFile is called and initiates and starts the player. NSLog testing will be called at the end of the method.
Now itβs strange if I call - (void)playSoundFile when the application is active, everything works fine, but if I start it with a background task, it just wonβt play sound.
Any help, hint, solution or heads-up is welcome.
Edit
So, I tried to use different threads at runtime, and as it seems, if Player is not created in the main thread, the same problem will appear. I also tried using AVPlayer and AVAudioPlayer , where the AVAudioPlayer .playing property returned YES and the sound was still not playing.
source share