引入系統(tǒng)框架
import <AVFoundation/AVFoundation.h>
import <AVKit/AVKit.h>
import <MediaPlayer/MediaPlayer.h>
//聲明相關(guān)屬性
@property (strong,nonatomic) AVPlayerViewController *playVC;
@property (strong,nonatomic) AVPlayer *player;
@property (strong,nonatomic) AVPlayerItem *item;
//播放視頻代碼
-
(void)onButton:(UIButton *)button {
//支持鎖屏的時候繼續(xù)播放
[[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設(shè)備的按鈕 MPVolumeView *volumeView = [[MPVolumeView alloc] init] ; volumeView.showsRouteButton = YES; volumeView.showsVolumeSlider = NO; volumeView.center = CGPointMake(100, 100); [[UIApplication sharedApplication].keyWindow addSubview:volumeView];
}];
}
//如果想在iPhone鎖屏的時候,AirPlay設(shè)備繼續(xù)播放,還需在Info.plist設(shè)置App的后臺模式支持AirPlay再扭。
Required background modes 里面添加 App plays audio or streams audio/video using AirPlay续捂!