Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to play youtube video using URL in AVPlayer IOS?

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];
}
like image 299
user2182231 Avatar asked Sep 09 '14 11:09

user2182231


2 Answers

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.

like image 149
dadederk Avatar answered Sep 21 '22 15:09

dadederk


  • Use XCDYouTubeKit pod
  • Get youtube video id from url like https://www.youtube.com/watch?v=dLEATulyCdw you can use this code:

    extension URL {
    
    func youtubeVideoId() -> String? {
    
        let pattern = #"(?<=(youtu\.be\/)|(v=)).+?(?=\?|\&|$)"#
        let testString = absoluteString
    
        if let matchRange = testString.range(of: pattern, options: .regularExpression) {
            let subStr = testString[matchRange]
            return String(subStr)
        } else {
            return .none
        }
    } }
    
  • Then call XCDYouTubeClient.default().getVideoWithIdentifier(videoId)

  • In the completion you can get url. video?.streamURLs contains urls with a different quality, choose desired.
  • Finally just pass this url to AVPlayer...

Update Visual explanation

enter image description here

Use first instead of youtubeMaxAvailableQuality

like image 23
Mike Glukhov Avatar answered Sep 18 '22 15:09

Mike Glukhov