Search code examples
iosavplayer

Get name of AirPlay device using AVPlayer


When AirPlay is enabled in a MPMoviePlayerController, it displays a text "This video is playing on device name ". When using AirPlay with an AVPlayer, is there any way to programatically get the device name?


Solution

  • After searching in other frameworks to get the name of the Apple TV you're connected to, I finally found this information in the AudioToolbox framework. There may be other ways to get this, but so far I have not found another way. Hope this helps.

    You'll need to import the AudioToolbox framework:

    #import <AudioToolbox/AudioToolbox.h>
    

    and then a method to call when you want to detect if airplay is available

    - (BOOL)isAirplayActive {
      CFDictionaryRef currentRouteDescriptionDictionary = nil;
      UInt32 dataSize = sizeof(currentRouteDescriptionDictionary);
      AudioSessionGetProperty(kAudioSessionProperty_AudioRouteDescription, &dataSize, &currentRouteDescriptionDictionary);
    
      self.deviceOutputType = nil;
      self.airplayDeviceName = nil;
    
      if (currentRouteDescriptionDictionary) {
        CFArrayRef outputs = CFDictionaryGetValue(currentRouteDescriptionDictionary, kAudioSession_AudioRouteKey_Outputs);
        if(CFArrayGetCount(outputs) > 0) {
          CFDictionaryRef currentOutput = CFArrayGetValueAtIndex(outputs, 0);
    
          //Get the output type (will show airplay / hdmi etc
          CFStringRef outputType = CFDictionaryGetValue(currentOutput, kAudioSession_AudioRouteKey_Type);
    
          //If you're using Apple TV as your ouput - this will get the name of it (Apple TV Kitchen) etc
          CFStringRef outputName = CFDictionaryGetValue(currentOutput, @"RouteDetailedDescription_Name");
    
          self.deviceOutputType = (NSString *)outputType;
          self.airplayDeviceName = (NSString *)outputName;
    
          return (CFStringCompare(outputType, kAudioSessionOutputRoute_AirPlay, 0) == kCFCompareEqualTo);
        }
      }
      return NO;
    }