如何检查设备是否通过airplay连接?

How to check if the device is connected via airplay?

我在检查我是否连接到 airplay 设备以及它是否通过镜像或流媒体连接时遇到了问题。但需要在视频开始前完成检查。

仅 airPlayVideoActive return YES 如果视频已经开始。

这是我的解决方案

- (BOOL)isAudioSessionUsingAirplayOutputRoute
{
    /**
     * I found no other way to check if there is a connection to an airplay device
     * airPlayVideoActive is NO as long as the video hasn't started 
     * and this method is true as soon as the device is connected to an airplay device
     */
    AVAudioSession* audioSession = [AVAudioSession sharedInstance];
    AVAudioSessionRouteDescription* currentRoute = audioSession.currentRoute;
    for (AVAudioSessionPortDescription* outputPort in currentRoute.outputs){
        if ([outputPort.portType isEqualToString:AVAudioSessionPortAirPlay])
            return YES;
    }
    return NO;
}

要检查 airplay 连接是否镜像,您只需检查屏幕数。

if ([[UIScreen screens] count] < 2)) {
    //streaming
}
else {
    //mirroring
}

如果有更好的解决办法,请告诉我

Swift版本:

var isAudioSessionUsingAirplayOutputRoute: Bool {

    let audioSession = AVAudioSession.sharedInstance()
    let currentRoute = audioSession.currentRoute

    for outputPort in currentRoute.outputs {
        if outputPort.portType == AVAudioSessionPortAirPlay {
            return true
        }
    }

    return false
}

并检查屏幕数:

if UIScreen.screens.count < 2 {
    //streaming
} else {
    //mirroring
}

如果您使用的是 AVPlayer,它有 属性 isExternalPlaybackActive 可以帮助您

致 Objc 上的可怜人

[[NSNotificationCenter defaultCenter]
    addObserver:self
    selector: @selector(deviceChanged:)
    name:AVAudioSessionRouteChangeNotification
    object:[AVAudioSession sharedInstance]];

- (void)deviceChanged:(NSNotification *)sender {
      NSLog(@"Enters here when connect or disconnect from Airplay");
}