2

My project related music and I have a problem stop playing music when turn off the screen. Although I registered background modes (Audio) but sometime when I turn off screen AVPlayer stopped playing music and played again when turn on the screen.

I spent a lot of time, but I can know why it happened.

Quang Dam
  • 305
  • 3
  • 15

1 Answers1

0

It's not enough to only add the audio background mode. You must also set a playback audio session category, as described in Apple QA1668:

A: You must declare your app plays audible content while in the background, and assign an appropriate category to your audio session.

#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>

AVAudioSession *audioSession = [AVAudioSession sharedInstance];

NSError *setCategoryError = nil;
BOOL success = [audioSession setCategory:AVAudioSessionCategoryPlayback error:&setCategoryError];
if (!success) { /* handle the error condition */ }

NSError *activationError = nil;
success = [audioSession setActive:YES error:&activationError];
if (!success) { /* handle the error condition */ }
Rhythmic Fistman
  • 34,352
  • 5
  • 87
  • 159
  • I have this and it still dies when the screen gets turned off. – TheJeff Oct 06 '18 at 19:31
  • This answer is incomplete: you must also be playing audio (or, oddly enough, recording). – Rhythmic Fistman Oct 06 '18 at 19:46
  • If this answer is incomplete, do you have a solution to complete it? Do you still experience the same issue? – TheJeff Oct 06 '18 at 19:48
  • Maybe the answer is ok for this question, as the question implies that music was playing... However are you playing video? The linked QA document https://developer.apple.com/library/archive/qa/qa1668/_index.html says that an `AVPlayer` playing video will be paused on transitioning to the background. Are you playing video? The QA suggests two work arounds for this. – Rhythmic Fistman Oct 06 '18 at 19:52
  • I'm playing audio already using AVPlayer and registeredBackgroundNotifications, then it transitions to background and continues playing. Then when the screen turns off the song stops playing. – TheJeff Oct 06 '18 at 20:07
  • Can you start a new question & show your `AVPlayer` and `AVAudioSession` configuration code & what you're doing with the background notifications? – Rhythmic Fistman Oct 06 '18 at 20:12
  • Will do. I'm going to verify I'm not getting an activation error first. Thanks. – TheJeff Oct 06 '18 at 20:14