How to play youtube video using URL in AVPlayer IO

2019-03-31 06:15发布

I want to load video in AVPlayer using YouTube URL but it is not showing anything.Whenever i am loading from a local storage using NSBundle it is working fine.Is there is any alternative to load video or we can do something in AVPlayer.

This is my code:

- (void)viewDidLoad
{
   [super viewDidLoad];
   NSError *setCategoryError = nil;
  [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error: &setCategoryError];
  AVAsset *asset = [AVAsset assetWithURL:[NSURL fileURLWithPath:@"http://www.youtube.com/watch?v=zPP6lXaL7KA&feature=youtube_gdata_player"]];
  avPlayerItem = [[AVPlayerItem alloc]initWithAsset:asset];
  self.songPlayer = [AVPlayer playerWithPlayerItem:avPlayerItem];
  self.avPlayerLayer = [AVPlayerLayer playerLayerWithPlayer: self.songPlayer];
  self.avPlayerLayer.frame = self.view.layer.bounds;
  UIView *newView = [[UIView alloc] initWithFrame:self.view.bounds];
  [newView.layer addSublayer:avPlayerLayer];
  [self.view addSubview:newView];
  [ self.songPlayer play];
}

2条回答
神经病院院长
2楼-- · 2019-03-31 06:35

I don't think if you can use this now because i just used this and encountered the same case.

I read the apple document-,it definitely refers to that (You cannot directly create an AVAsset instance to represent the media in an HTTP Live Stream.).

Instead here is apple's example:

NSURL *url = [NSURL URLWithString:@"<#Live stream URL#>];

// You may find a test stream at
http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8.

self.playerItem = [AVPlayerItem playerItemWithURL:url];

see,if not local url,should be playerItemWithURL:^_^

查看更多
仙女界的扛把子
3楼-- · 2019-03-31 06:53

You should use the iOS Youtube Helper library for playing youtube videos.

https://developers.google.com/youtube/v3/guides/ios_youtube_helper

I don't know if you can use the AVPlayer. I've seen some examples using MPMoviePlayerController on CocoaControls, like this one: https://www.cocoacontrols.com/controls/hcyoutubeparser or this one: https://www.cocoacontrols.com/controls/xcdyoutubevideoplayerviewcontroller

But I don't think using youtube's url directly in your player fits the ToS of the platform. So I will recommend you tu use the Youtube Helper Library if you are planning to publish your app.

查看更多
登录 后发表回答