iOS AirPlay投屏功能实现

作者: 心态别炸 | 来源:发表于2020-03-30 14:56 被阅读0次

    相信很部分人有点懵,网上帖子很多关于AirPlay,看完后还是有点不明白,怎么支持调试使用AirPlay来成功投屏!

    通俗易懂直接上
    首先AirPlay需要引入<MediaPlayer/MediaPlayer.h>

    self.volumView = [[MPVolumeView alloc] initWithFrame:view.bounds];
    
    [self.volumView setRouteButtonImage:[UIImage imageNamed:showForScreenImg] forState:UIControlStateNormal];
    
    self.volumView.showsVolumeSlider = NO;
    
    [viewaddSubview:self.volumView];
    

    前提有AirPlay设备可用,点击MPVolumeView弹出列表,选中可用设备,此时AirPlay已经连接成功。

    如何将音频、视频显示连接设备上

    NSURL *mediaUrl = [NSURL URLWithString:airPlayUrl];
    //为即将播放的视频内容进行建模
    self.item = [[AVPlayerItem alloc] initWithURL:mediaUrl];
    //给播放器赋值要播放的对象模型
    self.myPlayer = [AVPlayer playerWithPlayerItem:self.item];
    self.myPlayer.allowsExternalPlayback = YES;
    //指定显示的Layer
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.myPlayer];
    self.playerLayer.frame = self.bounds;
    [self.layer addSublayer:self.playerLayer];
    

    通过AVplay播放需要投屏的音视频即可。
    根据各App业务逻辑,正常实现快进快退、暂停开始即可控制电视端投屏内容。

    如何知道AirPlay的连接和断开状态?
    注册AVAudioSessionRouteChangeNotification通知,该通知在音频通道发生变化时会进行调用(例如插入/拔出耳机 扬声器/听筒切换 连接/断开AirPlay设备).这个的通知是唯一且不重复的.在发生改变时[AVAudioSession sharedInstance]会发送此通知.在具体通知中通过获取当前的AirPlay通道名称来判断是否连接到了投屏设备

     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioRouteHasChangedNotification:) name:AVAudioSessionRouteChangeNotification object:[AVAudioSession sharedInstance]];
    
    /**
        AVAudioSessionRouteChangeReasonKey = 1;
        AVAudioSessionRouteChangeReasonKey = 2;
        AVAudioSessionRouteChangeReasonKey = 4;
     **/
    - (void)audioRouteHasChangedNotification:(NSNotification *)notification{
        self.airplayDeviceName = [self airplayOutputRouteName];
        BOOL isAirPlay = self.airplayDeviceName.length > 0;
       
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([self.airPlayDelegate respondsToSelector:@selector(selectTvEquipmentStartAirPlay:)]) {
                [self.airPlayDelegate selectTvEquipmentStartAirPlay:self.airplayDeviceName];
            }
        });
    }
    //遍历当前设备所有通道.返回isEqualToString:AVAudioSessionPortAirPlay通道的具体名称,如果名称不为nil则为当前连接到了AirPlay
    - (NSString*)airplayOutputRouteName
    {
        AVAudioSession* audioSession = [AVAudioSession sharedInstance];
        AVAudioSessionRouteDescription* currentRoute = audioSession.currentRoute;
        for (AVAudioSessionPortDescription* outputPort in currentRoute.outputs){
            if ([outputPort.portType isEqualToString:AVAudioSessionPortAirPlay])
                return outputPort.portName;
        }
        return nil;
    }
    

    下次说:
    AirPlay连接过程中多个场景音视频,禁止播放某音视频。
    如何区分AirPlay与系统镜像投屏。

    相关文章

      网友评论

        本文标题:iOS AirPlay投屏功能实现

        本文链接:https://www.haomeiwen.com/subject/yhkvuhtx.html