AVAudioPlayer does not start playing in the background

I use AVAudioPlayerand NSFileHandlefor streaming audio. The basic idea is that I save streaming audio data to a device with a file system, and then use the file I just saved AVAudioPlayerto play. AVAudioPlayercan still play this file even in streaming mode.

I have UIButtonto start streaming / uploading. When the downloaded data is accumulated up to a certain number of bytes, it will be played AVAudioPlayer(the β€œplay” method starts automatically AVAudioPlayer). My question is: I press the button to start streaming playback / downloading, and then press the iPhone home button very soon so that my application goes to the background. The download continues to run in the background, but the "play" method AVAudioPlayerreturns "NO", which means that the "play" method does not play audio.

I added the related code AVAudioSessionto my audio player initialization method:

- (id) initWithURL:(NSString *) downloadedMusicURL
{
    if ((self = [super init]))
    {       
        [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

        CFURLRef url = CFURLCreateWithFileSystemPath (NULL, (CFStringRef)downloadedMusicURL, kCFURLPOSIXPathStyle, FALSE);

        audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:CFBridgingRelease(url) error:nil];

        AVAudioSession *session = [AVAudioSession sharedInstance];
        [session setActive:YES error:nil];
        [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    }

    return self;
}

info.plist "App play audio" " ". , "" - . ? .

0
4

. . , , , , ! , . , , !

, , , . ( ), - ; , .

, - , , , .

+2
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

UIBackgroundTaskIdentifier newTaskId = UIBackgroundTaskInvalid;
newTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL];

/* info.Plist : PLAYS Audio */

+1

, - (void)applicationDidEnterBackground:(UIApplication *)application

UIApplication *app = [UIApplication sharedApplication];
UIBackgroundTaskIdentifier bgTask = 0;

bgTask = [app beginBackgroundTaskWithExpirationHandler:^{ 
[app endBackgroundTask:bgTask]; 
}];
AudioSessionSetActive(false);

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

AudioSessionInitialize (NULL,NULL,NULL,NULL);
UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback;
AudioSessionSetProperty (kAudioSessionProperty_AudioCategory,sizeof (sessionCategory),&sessionCategory);
AudioSessionSetActive(true);

hope this helps.

0
source

Faced this same problem. Let me suggest you use AVAudioSessionCategoryOptionMixWithOthers with -setCategory: withOptions: error :. In addition, it may make sense to activate the session after installing the category, and not earlier.

0
source

All Articles