I try to embed different videos from youtube vimeo, dailymotion.
Sadly at the Moment nothing is shown except the backgroundcolor of my containerView:
UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0, 320.0f, 200.0f)];
//item.url is my url which i get fro my webserver, it looks like http://www.youtube.com/watch?v=zPP6lXaL7KA&feature=youtube_gdata_player
AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:[NSURL fileURLWithPath:item.url]];
AVPlayer *avPlayer = [AVPlayer playerWithPlayerItem:playerItem];
NSLog(#"%#",playerItem);
AVPlayerLayer *avPlayerLayer = [AVPlayerLayer playerLayerWithPlayer:avPlayer];
avPlayerLayer.frame = self.frame;
[containerView.layer addSublayer:avPlayerLayer];
[self addSubview:containerView];
[avPlayer play];
if (avPlayer.status == AVPlayerStatusReadyToPlay) {
//[playingLbl setText:#"Playing Audio"];
NSLog(#"It works");
} else if (avPlayer.status == AVPlayerStatusFailed) {
// something went wrong. player.error should contain some information
NSLog(#"Not works");
NSLog(#"%#",avPlayer.error);
}
else if (avPlayer.status == AVPlayerItemStatusUnknown) {
NSLog(#"AVPlayer Unknown");
}
containerView.backgroundColor = [UIColor blueColor];
NSLog(#"error: %#", avPlayer.error);
NSLog(#"AVPlayer: %#", avPlayer);
AVPlayer Error is Null and the only Log i always get from the Status is: AVPlayerItemStatusUnknown. Any ideas?
EDIT 1:
Ich changed my Code to:
#implementation VideoView
BlockVideo *list;
- (id)initWithBlock:(GFBlock *)block {
self = [super initWithBlock:block];
if (self) {
if (block.values && block.values.count) {
list = (GFBlockVideo *) [block.values objectAtIndex:0];
for (int i=0; i<list.videos.count; ++i) {
GFBlockVideoItem *item = list.videos[i];
UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0, 320.0f, 200.0f)];
//Like i said item.url = http://www.youtube.com/watch?v=zPP6lXaL7KA&feature=youtube_gdata_player
//#property (nonatomic, strong) NSString* url;
AVAsset *asset = [AVAsset assetWithURL:[NSURL URLWithString:item.url]];
AVPlayerItem *playerItem = [[AVPlayerItem alloc] initWithAsset:asset];
AVPlayer *avPlayer = [AVPlayer playerWithPlayerItem:playerItem];
AVPlayerLayer *avPlayerLayer = [AVPlayerLayer playerLayerWithPlayer:avPlayer];
avPlayerLayer.frame = containerView.frame;
[containerView.layer addSublayer:avPlayerLayer];
[self addSubview:containerView];
[avPlayer play];
containerView.backgroundColor = [UIColor blueColor];
Sadly the only thing i can see is the blue containerView :/
I think the Problem is not the AVPlayer himself, but the frames and the layer maybe....
You'd have to do the following:
AVAsset *asset = [AVAsset assetWithURL:[NSURL fileURLWithPath:item.url]];
AVPlayerItem *playerItem = [[AVPlayerItem alloc] initWithAsset:asset];
AVPlayer *avPlayer = [AVPlayer playerWithPlayerItem:playerItem];
AVPlayerLayer *avPlayerLayer = [AVPlayerLayer playerLayerWithPlayer:avPlayer];
avPlayerLayer.frame = self.frame;
[containerView.layer addSublayer:avPlayerLayer];
[self addSubview:containerView];
[avPlayer play];
Hope this helps.
Addendum:
It also depends on your URL; if as you said, you have one such as in this format:
http://www.youtube.com/watch?v=zPP6lXaL7KA&feature=youtube_gdata_player
Then you should use this instead:
[NSURL urlWithString:item.url];
Given that item is your object and url is a property there of object type NSString.
AVPlayer Implementation which working for me:
MP4:
player = [AVPlayer playerWithURL:videoPathUrl];
AVcontroller = [[AVPlayerViewController alloc] init];
[AVcontroller.view setFrame:CGRectMake(0, 0,self.view.frame.size.width, self.view.frame.size.width)];
AVcontroller.player = player;
AVcontroller.showsPlaybackControls = FALSE;
[self addChildViewController:AVcontroller];
[self.view addSubview:AVcontroller.view];
[player play];
MP3 :
playerItem = [AVPlayerItem playerItemWithURL:url];
player = [AVPlayer playerWithPlayerItem:playerItem];
player = [AVPlayer playerWithURL:url];
[player play];
For getting thumbnail form video try this
AVAsset *asset = [AVAsset assetWithURL:videoPathUrl];
AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc]initWithAsset:asset];
float tempTime = CMTimeGetSeconds(player.currentItem.duration);
CMTime time = CMTimeMake(tempTime, 1); // (1,1)
CGImageRef imageRef = [imageGenerator copyCGImageAtTime:time actualTime:NULL error:NULL];
UIImage *aThumbnail = [UIImage imageWithCGImage:imageRef];
For Stop Video
[player pause];
player = nil;
**Setting Play rate/Speed for video **
[player play];
[player setRate:currentRate];
Play From start
[player seekToTime:kCMTimeZero];
[player play];
for checking video is playing or not
if ((player.rate != 0) && (player.error == nil)) {
// playing
}
For seeking video (for some duration ahead)
float tempSeekTime = CMTimeGetSeconds(player.currentItem.duration) + 10;
CMTime targetTime = CMTimeMakeWithSeconds(tempSeekTime, NSEC_PER_SEC);
[player seekToTime:targetTime];
Use the requestPlayerItemForVideo method of PHImageManager to acquire an AVPlayerItem; it is the simplest, sure-fire way to play an AVAsset, performing flawlessly and consistently.
I use it here:
https://youtu.be/7QlaO7WxjGg
Related
Is it possible to display AVPlayerLayer inside a UIViewController which is later on displayed in UIView.
The sample code of what I'm trying to do:
...
UIView *parentView = reinterpret_cast<UIView *>(window->winId());
AVPlayer *_player;
AVURLAsset *_asset;
AVPlayerItem *_playerItem;
AVPlayerLayer *m_playerLayer;
_player = [[AVPlayer alloc] init];
NSURL *baseURL = [[NSURL alloc] initWithString: #"http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8"];
_asset = [AVURLAsset assetWithURL:baseURL];
_playerItem = [AVPlayerItem playerItemWithAsset: _asset];
[_player replaceCurrentItemWithPlayerItem:_playerItem];
m_playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
// works with AVPlayerViewController
// AVPlayerViewController *playerController = [[AVPlayerViewController alloc] init];
// playerController.player = _player;
UIViewController *viewController = [[UIViewController alloc] init];
[viewController.view.layer addSublayer:m_playerLayer];
viewController.view.frame = CGRectMake(this->x(), this->y(), this->width(), this->height());
[parentView addSubview:viewController.view];
[_player play];
...
It works if I try to add the player to AVPlayerViewController and then display it, but I would want to use only AVPlayerLayer since I don't need video controls as I'll implement the functionality separately.
You can use AVPlayerViewController with
avController.showsPlaybackControls = false;
Or simply add the layer
_player = [[AVPlayer alloc] init];
NSURL *baseURL = [[NSURL alloc] initWithString: #"http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8"];
_asset = [AVURLAsset assetWithURL:baseURL];
_playerItem = [AVPlayerItem playerItemWithAsset: _asset];
[_player replaceCurrentItemWithPlayerItem:_playerItem];
m_playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
m_playerLayer.frame = self.view.bounds;
[self.view.layer addSublayer:m_playerLayer ];
[_player play];
I subclassed UIView and added on the AVPlayerLayer via SH_Khans method
_player = [[AVPlayer alloc] init];
NSURL *baseURL = [[NSURL alloc] initWithString: #"http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8"];
_asset = [AVURLAsset assetWithURL:baseURL];
_playerItem = [AVPlayerItem playerItemWithAsset: _asset];
[_player replaceCurrentItemWithPlayerItem:_playerItem];
m_playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
m_playerLayer.frame = self.view.bounds;
[self.view.layer addSublayer:m_playerLayer ];
[_player play];
Then treat the subclassed UIView how you want. Couple of things though, if you resize the AVPlayerLayerUIView you have to resize the AVPlayerLayer as the system does not do that automatically.
Additionally remember to clip to bounds on the AVPlayerLayerUIView or it will not match your frame as you want.
In my application ai have loaded all video url's to AVPlayer and it has previous and next buttons here i have setup player
-(void)setUpMyNewPlayer
{
[self addTimer];
NSURL *url=[NSURL URLWithString:_videosArray[0]];
_currentIndex =0;
videoPlayer = [[AVPlayer alloc]init]; //WithPlayerItem:_avPlayerItem];
videoPlayer.automaticallyWaitsToMinimizeStalling = NO;
AVAsset *asset = [AVAsset assetWithURL:url];
[asset loadValuesAsynchronouslyForKeys:#[#"playable"] completionHandler:^{
AVPlayerItem *item = [AVPlayerItem playerItemWithAsset:asset];
videoPlayer = [AVPlayer playerWithPlayerItem:item];
AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:videoPlayer];
playerLayer.videoGravity = AVLayerVideoGravityResize;
playerLayer.frame = CGRectMake(0, 0, self.playView.frame.size.width, self.playView.frame.size.height);
[self.playView.layer addSublayer:playerLayer];
[videoPlayer play];
CMTime interval = CMTimeMakeWithSeconds(0.5, NSEC_PER_SEC);
dispatch_queue_t mainQueue = dispatch_get_main_queue();
__weak typeof(self) weakSelf = self;
[videoPlayer addPeriodicTimeObserverForInterval:interval
queue:mainQueue
usingBlock:^(CMTime time) {
// Use weak reference to self
if (_currentIndex==_contentImages.count-1) {
weakSelf.nextButton.hidden=YES;
weakSelf.previousButton.hidden=NO;
}
else if (_currentIndex==0)
{
weakSelf.previousButton.hidden=YES;
if (_contentImages.count>1) {
weakSelf.nextButton.hidden=NO;
}
else
{
weakSelf.nextButton.hidden=YES;
}
}
else if (_currentIndex>0 && _currentIndex!=_contentImages.count-1)
{
// NSLog(#"Showing Both");
weakSelf.nextButton.hidden=NO;
weakSelf.previousButton.hidden=NO;
}
}];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(itemDidFinishPlaying1:) name:AVPlayerItemDidPlayToEndTimeNotification object:item];
}];
}
-(void)itemDidFinishPlaying1:(NSNotification *) notification {
//
// Will be called when AVPlayer finishes playing playerItem
if (_currentIndex == _videosArray.count-1) {
}
else{
_currentIndex = _currentIndex+1;
NSURL *url=[NSURL URLWithString:_videosArray[_currentIndex]];
AVAsset *asset = [AVAsset assetWithURL:url];
AVPlayerItem *item = [AVPlayerItem playerItemWithAsset:asset];
[videoPlayer replaceCurrentItemWithPlayerItem:item];
[self changePage:UIPageViewControllerNavigationDirectionForward];
[self addTimer];
}
}
-(void)addTimer
{
myTimer = [NSTimer scheduledTimerWithTimeInterval: 0.1 target: self
selector: #selector(callAfterOneSecond1:) userInfo: nil repeats: YES];
}
-(void) callAfterOneSecond1:(NSTimer*)t
{
[[AppDelegate shared] showLoading];
if (videoPlayer.rate !=0 && videoPlayer.error == nil && videoPlayer.status == AVPlayerStatusReadyToPlay) {
[[AppDelegate shared]removeLoading];
[myTimer invalidate];
myTimer=nil;
}
}
pragma mark- PreviousAction
- (IBAction)previousButtonAction:(id)sender {
if (_currentIndex == 0) {
}
else{
_currentIndex = _currentIndex-1;
NSURL *url=[NSURL URLWithString:_videosArray[_currentIndex]];
AVAsset *asset = [AVAsset assetWithURL:url];
AVPlayerItem *item = [AVPlayerItem playerItemWithAsset:asset];
[videoPlayer replaceCurrentItemWithPlayerItem:item];
[videoPlayer play];
[self changePage:UIPageViewControllerNavigationDirectionReverse];
[self addTimer];
}
}
pragma mark- NextAction
- (IBAction)nextButtonAction:(id)sender {
if (_currentIndex == _videosArray.count-1) {
}
else{
_currentIndex = _currentIndex+1;
NSURL *url=[NSURL URLWithString:_videosArray[_currentIndex]];
AVAsset *asset = [AVAsset assetWithURL:url];
AVPlayerItem *item = [AVPlayerItem playerItemWithAsset:asset];
[videoPlayer replaceCurrentItemWithPlayerItem:item];
[videoPlayer play];
[self changePage:UIPageViewControllerNavigationDirectionForward];
[self addTimer];
}
}
Here the player is playing well but with small delay. . How to load next coming video while playing current video without delay.
I'm a bit rusty and the iOS documentation on the whole of AVFoundation is woefully inadequate if you want to do anything slightly complicated. Its been a while since I did this but something like this should work (I'm assuming you have an NSArray*, pAssets containing all your videos as AVAsset*)
// Define the composition.
AVMutableComposition* pComposition = [AVMutableComposition composition];
// Define the tracks in the composition.
AVMutableCompositionTrack* pCompositionVideoTrack = [pComposition addMutableTrackWithMediaType: AVMediaTypeVideo preferredTrackID: 1];
AVMutableCompositionTrack* pCompositionAudioTrack = [pComposition addMutableTrackWithMediaType: AVMediaTypeAudio preferredTrackID: 2];
CMTime time = kCMTimeZero;
for ( AVAsset* pAssetsAsset in pAssets )
{
// Grab first video and audio tracks
AVAssetTrack* pAssetsAssetVideoTrack = [pAssetsAsset tracksWithMediaType: AVMediaTypeVideo].firstObject;
AVAssetTrack* pAssetsAssetAudioTrack = [pAssetsAsset tracksWithMediaType: AVMediaTypeAudio].firstObject;
// Get time range of entire video.
CMTimeRange timeRange = CMTimeRangeMake( kCMTimeZero, timepAssetsAsset.duration );
// Insert the entire video and audio into their respective tracks at "time".
NSError* pVideoError = nil;
NSError* pAudioError = nil;
[pCompositionVideoTrack insertTimeRange: timeRange ofTrack: pAssetsAssetVideoTrack atTime: time error: &pVideoError];
[pCompositionAudioTrack insertTimeRange: timeRange ofTrack: pAssetsAssetAudioTrack atTime: time error: &pAudioError];
// Move time along appropriately.
time = CMTimeAdd( time, pAssetsAsset.duration );
}
If you then pass the AVMutableComposition is derived from AVAsset so you can use this as normal and drop it into an AVPlayer (via an AVPlayerItem).
Now you can seek to any point in the video. Store the start/finish points of each video and you can easily seek to it.
Edit: Its ultra simple to use AVPlayer. First you need to create an AVPlayerItem .. and then you need to play it.
AVPlayerItem* pPlayerItem = [AVPlayerItem playerItemWithAsset: pComposition];
AVPlayer* pPlayer = [AVPlayer playerWithPlayerItem: pPlayerItem];
Now you need to attach it to a view's layer. So from inside your ViewController do something like this:
AVPlayerLayer* pLayer = [AVPlayerLayer playerLayerWithPlayer: pPlayer];
[self.view.layer addSublayer: pLayer];
Use AVQueuePlayer instead of simple AVPlayer. At the end of current video it will preload next video.
See how to use AVQueuePlayer here: https://stackoverflow.com/a/22785665/1271424
When i click my local video url and present Viewcontroller and Play video in AVPlayer.Play 14-15 times and Player crash.Avplayer showing like
- (void)viewDidLoad
{
[self PlayVideoinPlayer:_videoURL];
}
-(void)PlayVideoinPlayer:(NSString *)URL
{
NSURL *fileURL = [NSURL fileURLWithPath:URL];
_Avcontroller=[[AVPlayerViewController alloc]init];
asset = [AVURLAsset URLAssetWithURL:fileURL options:nil];
anItem = [AVPlayerItem playerItemWithAsset:asset];
_avPlayer = [AVPlayer playerWithPlayerItem:anItem];
[_avPlayer addObserver:self forKeyPath:#"status" options:0 context:nil];
self.Avcontroller.view.frame = self.view.bounds;
[self.Avcontroller setPlayer:_avPlayer];
_Avcontroller.videoGravity=AVLayerVideoGravityResizeAspectFill;
[self.view addSubview:self.Avcontroller.view];
[self.view addSubview:self.Avcontroller.view];
[_avPlayer play];
CMTime interval = CMTimeMake(1, 1800);
__strong __typeof(self) weakself = self;
playbackObserver = [_avPlayer addPeriodicTimeObserverForInterval:interval queue:dispatch_get_main_queue() usingBlock: ^(CMTime time) {
CMTime endTime = CMTimeConvertScale (_avPlayer.currentItem.asset.duration, _avPlayer.currentTime.timescale, kCMTimeRoundingMethod_RoundHalfAwayFromZero);
if (CMTimeCompare(endTime, kCMTimeZero) != 0)
{
// double normalizedTime = (double) avPlayer.currentTime.value / (double) endTime.value;
//NSLog(#"--------->>>>%#",playbackObserver);
}
int CurrentSecond=[[weakself getStringFromCMTime:_avPlayer.currentTime] intValue];
_avPlayer.rate=1.0f;
}
Anyone have solution.? Please help me.Thanks
I am using MPMoviePlayer to display a video from an external URL onto my iPhone App, however when I run the App a black screen is all that shows.
Here is the URL I am using:
2015-04-27 00:11:29.655 Floadt[21069:2598414] https://scontent.cdninstagram.com/hphotos-xaf1/t50.2886-16/11179443_819874424728492_389701720_n.mp4
Here is my code to try to setup MPMoviePlayer:
if (entry[#"videos"] != nil) {
NSLog(#"There is a Video: %#", entry[#"videos"]);
NSString *urlString = entry[#"videos"][#"standard_resolution"][#"url"];
NSLog(urlString);
NSURL *url = [NSURL URLWithString:urlString];
MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL: url];
[player prepareToPlay];
[player.view setFrame: CGRectMake(10, 65, 299, 299)];
[cell.contentView addSubview: player.view];
player.shouldAutoplay = YES;
[player play];
}
You need to retain your instance to MPMoviePlayerController i.e. as a property or an instance variable. The reference to the movie player is lost if you do not retain.
When we try to load the video from URL initially it will display blank screen only. MPMoviePlayerController will take some time to load the video from url.So we can display first frame of the video till the video loads. For this need to import two frameworks.
1.AVFoundation
2.AssetsLibrary
Using these two we can display first frame of video into UIImageView as follows:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
url=[NSURL URLWithString:#"https://scontent.cdninstagram.com/hphotos-xaf1/t50.2886-16/11179443_819874424728492_389701720_n.mp4"];
AVAsset *avAsset = [AVURLAsset URLAssetWithURL:url options:nil];
if ([[avAsset tracksWithMediaType:AVMediaTypeVideo] count] > 0)
{
AVAssetImageGenerator *imageGenerator =[AVAssetImageGenerator assetImageGeneratorWithAsset:avAsset];
Float64 durationSeconds = CMTimeGetSeconds([avAsset duration]);
CMTime midpoint = CMTimeMakeWithSeconds(durationSeconds/2.0, 600);
NSError *error;
CMTime actualTime;
CGImageRef halfWayImage = [imageGenerator copyCGImageAtTime:kCMTimeZero actualTime:&actualTime error:&error];
if (halfWayImage != NULL)
{
NSString *actualTimeString = (NSString *)CFBridgingRelease(CMTimeCopyDescription(NULL, actualTime));
NSString *requestedTimeString = (NSString *)CFBridgingRelease(CMTimeCopyDescription(NULL, midpoint));
NSLog(#"Got halfWayImage: Asked for %#, got %#", requestedTimeString, actualTimeString);
UIImage *img=[UIImage imageWithCGImage:halfWayImage];
_imgVw.image=img;
}
}
UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:#selector(tapped)];
[_imgVw addGestureRecognizer:tap];
}
-(void)tapped
{
MPMoviePlayerController *movPlayer=[[MPMoviePlayerController alloc] init];
[movPlayer setContentURL:url];
[movPlayer setMovieSourceType:MPMovieSourceTypeFile];
[movPlayer.view setFrame:CGRectMake(0, 0, _imgVw.frame.size.width, 250)];
[movPlayer prepareToPlay];
movPlayer.controlStyle = MPMovieControlStyleNone;
movPlayer.fullscreen = NO;
movPlayer.shouldAutoplay=YES;
[movPlayer setScalingMode:MPMovieScalingModeAspectFill];
[_imgVw addSubview:movPlayer.view];
[movPlayer play];
}
Here i am taking UIImageView view for playing the video. In viewDidLoad i am loading the 1st frame and giving tap gesture to the UIImageView. When i tapped the ImageView then i am playing the video.
MPMoviePlayerController * _moviePlayerController = [[MPMoviePlayerController alloc] init];
_moviePlayerController.controlStyle = MPMovieControlStyleDefault;
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"test" ofType:#"mp4"]];
_moviePlayerController.contentURL = url;
_moviePlayerController.fullscreen=NO;
_moviePlayerController.backgroundView.backgroundColor = [UIColor whiteColor];
for(UIView *aSubView in _moviePlayerController.view.subviews) {
aSubView.backgroundColor = [UIColor whiteColor];
}
// Rotating the player to landscape position
_moviePlayerController.view.frame = CGRectMake(0.0f,
0.0f,
[UIScreen mainScreen].bounds.size.width,
[UIScreen mainScreen].bounds.size.height);
// _moviePlayerController.view.transform = CGAffineTransformMakeRotation(M_PI_2);
_moviePlayerController.view.center = self.view.center;
UIView *playerView = _moviePlayerController.view;
playerView.frame = CGRectMake(0.0f,
0.0f,
[UIScreen mainScreen].bounds.size.width,
[UIScreen mainScreen].bounds.size.height);
[videoPlayerView addSubview:playerView];
_moviePlayerController.shouldAutoplay=NO;
[_moviePlayerController prepareToPlay];
[_moviePlayerController pause];
Its not possible to mute your audio player by using MPMoviePlayerController. If you want to mute your audio player you should add AVFoundation framework. Try this code
AVURLAsset * asset = [AVURLAsset URLAssetWithURL:[self localMovieURL] options:nil];
NSArray *audioTracks = [asset tracksWithMediaType:AVMediaTypeAudio];
// Mute all the audio tracks
NSMutableArray * allAudioParams = [NSMutableArray array];
for (AVAssetTrack *track in audioTracks) {
AVMutableAudioMixInputParameters *audioInputParams =[AVMutableAudioMixInputParameters audioMixInputParameters];
[audioInputParams setVolume:0.0 atTime:kCMTimeZero ];
[audioInputParams setTrackID:[track trackID]];
[allAudioParams addObject:audioInputParams];
}
AVMutableAudioMix * audioZeroMix = [AVMutableAudioMix audioMix];
[audioZeroMix setInputParameters:allAudioParams];
// Create a player item
AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:asset];
[playerItem setAudioMix:audioZeroMix]; // Mute the player item
// Create a new Player, and set the player to use the player item
// with the muted audio mix
AVPlayer *player = [AVPlayer playerWithPlayerItem:playerItem];
self.mPlayer = player;
[mPlayer play];