Note that there are some explanatory texts on larger screens.

plurals
  1. POstart playing audio from a background task via AVAudioPlayer in XCode
    text
    copied!<p>I am trying to start playing a sound from a background task via an AVAudioPlayer that is instantiated then, so here's what I've got.</p> <p>For readability I cut out all user selected values.</p> <pre><code>- (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] &gt;= difference) { [self playSoundFile]; [tim invalidate]; [[UIApplication sharedApplication] endBackgroundTask:bg]; } } - (void)playSoundFile { NSError *sessionError = nil; [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&amp;sessionError]; // new player object _player = [[AVQueuePlayer alloc] init]; [_player insertItem:[AVPlayerItem playerItemWithURL:[[NSBundle mainBundle] URLForResource:@"Manamana" withExtension:@"m4a"]] afterItem:nil]; [_player setVolume:.7]; [_player play]; NSLog(@"Testing"); } </code></pre> <p>Explanation: <code>bg</code>, <code>tim</code>, <code>startDate</code>, <code>difference</code> and <code>_player</code> are globally declared variables. I call <code>- (void)restartHandler</code> from a user-fired method and inside it start a 10Hz repeating timer for <code>- (void)upd</code>. When a pre-set difference is reached, <code>- (void)playSoundFile</code> gets called and initiates and starts the player. The testing NSLog at the end of the method gets called.</p> <p>Now the strange thing is if I call <code>- (void)playSoundFile</code> when the app is active, everything works out just fine, but if I start it from the background task it just won't play any sound.</p> <p>Any help, hint, solution or heads up is greatly appreciated. </p> <p><strong>Edit</strong></p> <p>So I tried using different threads at runtime and as it seems, if the Player is not instantiated on the Main Thread this same problem will appear. I also tried using <code>AVPlayer</code> and <code>AVAudioPlayer</code> where the <code>AVAudioPlayer</code>'s <code>.playing</code> property did return YES and still no sound was playing.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload