问题
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];
}
回答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.
回答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
Use first
instead of youtubeMaxAvailableQuality
回答3:
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
:^_^
来源:https://stackoverflow.com/questions/25743208/how-to-play-youtube-video-using-url-in-avplayer-ios