Search code examples
iphonexcodeios6avplayerairplay

Airplay using AVPlayer does not always work. 'iPhone' option listed twice in the Airplay menu


NSError *sessionError = nil;
[[AVAudioSession sharedInstance] setDelegate:self];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&sessionError];
[[AVAudioSession sharedInstance] setActive:YES error:nil];

//Direct audio to speakers when there is no headphone
UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback;
AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(sessionCategory), &sessionCategory);
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,sizeof (audioRouteOverride),&audioRouteOverride);

[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];


[player setAllowsExternalPlayback:YES];
[player setUsesExternalPlaybackWhileExternalScreenIsActive: YES];
[player setAllowsAirPlayVideo:NO];

The above is my code trying to set the appropriate session to enable Airplay. It works sometimes, but regardless of whether it works or not, it usually lists 'iPhone' twice please see the attached image in the Airplay menu, sometimes not showing the actual Airplay device. Tapping either of those two duplicate options does not seem to do anything. Also the play icon on the status bar sometimes appears, and sometimes it doesn't. I am guessing the session is not getting set properly every time.

Can anybody kindly tell me what I am doing wrong here?! Also, if I want to enable playing over Bluetooth, do I need to implement some other delegate?


Solution

  • I see your post today, using your code in this mode:

    In your AppDelegate .M this:

    NSError *sessionError = nil;
    [[AVAudioSession sharedInstance] setDelegate:self];
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
    [[AVAudioSession sharedInstance] setActive:NO error:nil];
    
    UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback;
    AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(sessionCategory), &sessionCategory);
    
    UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
    AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,sizeof (audioRouteOverride),&audioRouteOverride);
    
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    

    And in your View.m using this:

    [player setAllowsExternalPlayback:YES];
    [player setUsesExternalPlaybackWhileExternalScreenIsActive: YES];
    [player setAllowsAirPlayVideo:NO];//this is deprecated in iOS 6.0
    

    Hope this help you or future people!