How to play youtube video using URL in AVPlayer IOS?

18,080

Solution 1

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.

Solution 2

  • 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

Share:
18,080
user2182231
Author by

user2182231

Updated on June 19, 2022

Comments

  • user2182231
    user2182231 almost 2 years

    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];
    }