美文网首页
AVPlayerViewController 通过AirPaly

AVPlayerViewController 通过AirPaly

作者: LeLeBa | 来源:发表于2016-12-29 13:31 被阅读1072次

引入系统框架

import <AVFoundation/AVFoundation.h>

import <AVKit/AVKit.h>

import <MediaPlayer/MediaPlayer.h>

//声明相关属性
@property (strong,nonatomic) AVPlayerViewController *playVC;
@property (strong,nonatomic) AVPlayer *player;
@property (strong,nonatomic) AVPlayerItem *item;

//播放视频代码

  • (void)onButton:(UIButton *)button {

    //支持锁屏的时候继续播放
    [[AVAudioSession sharedInstance] setActive:YES error:nil];
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];

    NSString *strPath = [[NSBundle mainBundle] pathForResource:@"test1" ofType:@"mp4"];
    NSURL *url = [NSURL fileURLWithPath:strPath];
    AVAsset *asset = [AVAsset assetWithURL:url];
    self.item = [AVPlayerItem playerItemWithAsset:asset];
    self.player = [AVPlayer playerWithPlayerItem:self.item];
    self.playVC = [[AVPlayerViewController alloc] init];
    self.playVC.player = self.player;

    [[NSNotificationCenter defaultCenter] addObserver:self
    selector:@selector(playerItemDidReachEnd:)
    name:AVPlayerItemDidPlayToEndTimeNotification
    object:_item];

    self.player.allowsExternalPlayback = YES;
    self.player.usesExternalPlaybackWhileExternalScreenIsActive = YES;

    __weak typeof(self) weakSelf = self;
    [self presentViewController:self.playVC animated:YES completion:^{

      [weakSelf.player play];
      
      //添加选择AirPlay设备的按钮
      MPVolumeView *volumeView = [[MPVolumeView alloc] init] ;
      volumeView.showsRouteButton = YES;
      volumeView.showsVolumeSlider = NO;
      volumeView.center = CGPointMake(100, 100);
      [[UIApplication sharedApplication].keyWindow addSubview:volumeView];
    

    }];

}

//如果想在iPhone锁屏的时候,AirPlay设备继续播放,还需在Info.plist设置App的后台模式支持AirPlay。
Required background modes 里面添加 App plays audio or streams audio/video using AirPlay!

相关文章

网友评论

      本文标题:AVPlayerViewController 通过AirPaly

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