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];
}
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.
XCDYouTubeKit
podGet 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)
video?.streamURLs
contains urls with a different quality, choose desired.Update Visual explanation
Use first
instead of youtubeMaxAvailableQuality
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With