iCarousel AVPlayerItem Instances not displaying correctly - ios

What I am trying to achieve
I would like to display a carousel of videos that play independently. No more than 10 at a time. as well as having their own play button per carousel object to play independently.
What I am getting
After 3 Items display in the carousel it displays the same three over and over again until it reaches the end of the 10 items.
I am assigning the AVAsset like below:
AVURLAsset *asset = [AVURLAsset URLAssetWithURL:[NSURL URLWithString:[_videoURLS objectAtIndex:index]] options:nil];
_videoURLS is an NSMutableArray of NSStrings it returns a 10 count to populate 10 items in the carousel like below.
- (NSUInteger)numberOfItemsInCarousel:(iCarousel *)carousel
{
//return the total number of items in the carousel
return [_videoURLS count];
}
Now to populate the Video View I am doing the below:
- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSUInteger)index reusingView:(UIView *)view
{
AVURLAsset *asset = [AVURLAsset URLAssetWithURL:[NSURL URLWithString:[_videoURLS objectAtIndex:index]] options:nil];
//create new view if no view is available for recycling
if (view == nil)
{
//don't do anything specific to the index within
//this `if (view == nil) {...}` statement because the view will be
//recycled and used with other index values later
UIView *mainView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200.0f, 370.0f)];
view = mainView;
CGFloat mainViewWidth = mainView.bounds.size.width;
//Video Player View
_videoView = [[UIView alloc] initWithFrame:CGRectMake(0,0, mainViewWidth, 220)];
_videoView.backgroundColor = [UIColor colorWithRed:123/255.0 green:123/255.0 blue:123/255.0 alpha:1.0];
_videoView.center = CGPointMake(100, 170);//170
_videoView.tag = 20;
[view addSubview:_videoView];
//AV Asset Player
AVPlayerItem * playerItem = [[AVPlayerItem alloc] initWithAsset:asset];
_player = [[AVPlayer alloc] initWithPlayerItem:playerItem];
AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
playerLayer.frame = _videoView.bounds;
[_videoView.layer addSublayer:playerLayer];
[_player seekToTime:kCMTimeZero];
//Play Button
_playButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 60.0f, 60.0f)];
[_playButton setBackgroundImage:[UIImage imageNamed:#"play-icon-grey.png"] forState:UIControlStateNormal];
[_playButton addTarget:self action:#selector(playVideo:) forControlEvents:UIControlEventTouchUpInside];
_playButton.center = CGPointMake(100, 160);
_playButton.tag = 1;
[view addSubview:_playButton];
}
else
{
//get a reference to the label in the recycled view
_playButton = (UIButton *) [view viewWithTag:1];
_videoView = (UIView *) [view viewWithTag:20];
}
//set item label
//remember to always set any properties of your carousel item
//views outside of the `if (view == nil) {...}` check otherwise
//you'll get weird issues with carousel item content appearing
//in the wrong place in the carousel
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(didFinishPlaying:) name:MPMoviePlayerPlaybackDidFinishNotification object:_player];
return view;
}
I handle the play button like below:
-(IBAction)playVideo:(id)sender {
if (_playButton.isHidden) {
[_playButton setHidden:NO];
}else{
[_playButton setHidden:YES];
[_player play];
}
}
Though when I press the play button it plays the second video in the carousel.
What is the proper way to handle this and have all the videos play single handed?

Related

Remove contant of a previous page when next load in collection view in paging

I am using a UICollectionView with paging feature and adding AVPlayer on each cell to play video with URL, but my collection view is giving a strange behavior. When it loads the first cell and video starts playing then it is fine but when I slide and load the next cell then both videos are playing together, while I want the previous one to stop playing. I tried many thing to resolve this issue but nothing is working, someone please suggest me something to work with this. My code of custom cell class where I am adding AVPlayer is given below:
[self.avPlayer pause];
self.avPlayer = nil;
[self.avLPlayer removeFromSuperlayer];
CGRect videoRect;
videoRect = CGRectMake(0,0,[[UIScreen mainScreen]bounds].size.width,[[UIScreen mainScreen]bounds].size.height);
UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
[indicator startAnimating];
[indicator bringSubviewToFront:_viewForShowVideo];
UIWindow* currentWindow = [UIApplication sharedApplication].keyWindow;
indicator.frame = CGRectMake(currentWindow.frame.size.width/2, _viewForShowVideo.frame.size.height/2, 20, 20);
[_viewForShowVideo addSubview:indicator];
self.avPlayerItem = [AVPlayerItem playerItemWithURL:Url];
self.avPlayer = [AVPlayer playerWithPlayerItem:self.avPlayerItem];
self.avLPlayer = [AVPlayerLayer playerLayerWithPlayer:self.avPlayer];
[_avLPlayer setFrame:videoRect];
[_avLPlayer setBackgroundColor:[UIColor blackColor].CGColor] ;
[_avLPlayer setVideoGravity:AVLayerVideoGravityResizeAspect];
_avLPlayer.opacity = 1;
_avPlayer.allowsExternalPlayback = NO;
[_avPlayer setMuted:NO];
_avPlayer.actionAtItemEnd = AVPlayerActionAtItemEndNone;
[[AVAudioSession sharedInstance]setCategory: AVAudioSessionCategoryPlayback error: nil];
[_viewForShowVideo.layer addSublayer:_avLPlayer];
[_avPlayer play];
UITapGestureRecognizer *tgr = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(tapOnPlayer:)];
[_viewForShowVideo addGestureRecognizer:tgr];
[_viewForShowVideo setBackgroundColor:[UIColor greenColor]];

XCode - Getting videos to play in tableview cells like Vine & Instagram

I'm trying to get a vine type video feed working in a tableview. I want the videos to play one at a time inside the tableview cell just like Vine and Instagram.
Does anyone know how to do this? I'm using MPMoviePlayer.
Thanks
---- UPDATE ----
I've got the auto-play call-to-action working well (please see 'Play this one') when each table cell is in the center but I'm having trouble getting multiple MPMoviePlayers to load/stop/play.
I only require one video to play in its cell at any one time but I can only seem to get the video in the first cell playing and it is not responding to the Stop call (please see 'Don't play this one' ).
Below is a snippet of my script. The only part not working is getting the videos to actually play and stop. The call to play and stop works fine.
I have this in my CellForRow:
MPMoviePlayerViewController *videoPlayer;
[videoPlayer.view removeFromSuperview];
videoPlayer = [[MPMoviePlayerViewController alloc] init];
int videoTag = 500+indexPath.row;
[videoPlayer.view setTag:videoTag];
videoPlayer.moviePlayer.repeatMode = MPMovieRepeatModeOne;
videoPlayer.moviePlayer.controlStyle = MPMovieControlStyleNone;
videoPlayer.view.frame = CGRectMake( 0, 0, 320, 320);
[videoPlayer.view setBackgroundColor:[UIColor whiteColor]];
[playerView addSubview:videoPlayer.view];
And I do this for calling the correct cell in the center of the view:
- (void)scrollViewDidScroll:(UIScrollView *)theView{
UITableViewCell *cell = (UITableViewCell *) theView;
CGPoint currentOffset = theView.contentOffset;
for (UITableViewCell *cell in [videoTableView visibleCells]) {
NSIndexPath *indexPath = [videoTableView indexPathForCell:cell];
int videoTag = 500+indexPath.row;
MPMoviePlayerViewController *videoPlayer = (MPMoviePlayerViewController *)[cell viewWithTag:videoTag];
UILabel *test_label = (UILabel *)[cell viewWithTag:300];
CGRect cellRect = [videoTableView convertRect:cell.bounds fromView:cell];
int scrollPosition = currentOffset.y + 64; // 64px is the navigation bar height
int cellPosition = cellRect.origin.y;
if( scrollPosition > cellPosition-100 && scrollPosition < cellPosition+100 )
{
test_label.text = [NSString stringWithFormat:#"Play this one" ];
UIView *blankOut = (UIView *)[cell viewWithTag:200];
UIView *playerView = (UIView *)[cell viewWithTag:201];
UIImageView *videoCoverUp = (UIImageView *)[cell viewWithTag:202];
[playerView.layer setCornerRadius:138];
[playerView.layer setMasksToBounds:YES];
if(_isPlaying!=true){
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"video.mp4"];
NSData *video_data = _tableObjects[indexPath.row][9];// Where my video data is stored
[video_data writeToFile:path atomically:YES];
NSURL *moveUrl = [NSURL fileURLWithPath:path];
videoPlayer.moviePlayer.contentURL = moveUrl;
[videoPlayer.moviePlayer prepareToPlay];
[videoPlayer.moviePlayer play];
_isPlaying = true;
// Needed
[[UIApplication sharedApplication] setStatusBarHidden:NO];
[self setNeedsStatusBarAppearanceUpdate];
}
} else {
test_label.text = [NSString stringWithFormat:#"Don't play this one" ];
[videoPlayer.moviePlayer stop];
[videoPlayer.moviePlayer setContentURL:[NSURL URLWithString:nil]];
[videoPlayer.moviePlayer prepareToPlay];
//[_videoPlayer.moviePlayer.view removeFromSuperview];
_isPlaying = false;
}
}
}
The MPMoviePlayer manual seems to describe what to do?
https://developer.apple.com/library/prerelease/ios/documentation/MediaPlayer/Reference/MPMoviePlayerController_Class/index.html
It shows you what to do right at the top. Seems you will just need a cell with a view in it for you to add the movie player to.
MPMoviePlayerController *player =
[[MPMoviePlayerController alloc] initWithContentURL: myURL];
[player prepareToPlay];
[player.view setFrame: myView.bounds]; // player's frame must match parent's
[myView addSubview: player.view];
// ...
[player play];
As per the comment, google is your friend. Must be lots of examples out there.

Loading MPMovieControl for ICarousel Not Working Correctly

I am trying to achieve a iCarousel of Video URLS to allow users to see others posts.
Now i have to say i love iCarousel and this has been my only issue with it.
I have the right number of carousel objects showing up and the play button is on all of them though i'm only receiving one video at a time and the controls are not playing the video properly.
I have an NSMutableArray in place holding the _videoURLS, this is where i provide the number of carousel objects that need to be via [_videoURLS count];
In my .m file this is how i am preparing the video player with the carousel object
- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSUInteger)index reusingView:(UIView *)view
{
if (view == nil)
{
UIView *mainView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200.0f, 370.0f)];
view = mainView;
CGFloat mainViewWidth = mainView.bounds.size.width;
//Video Player View
_videoView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, mainViewWidth, 220)];
_videoView.backgroundColor = [UIColor colorWithRed:123/255.0 green:123/255.0 blue:123/255.0 alpha:1.0];
_videoView.center = CGPointMake(100, 170);
_videoView.tag = 7;
[view addSubview:_videoView];
//video
_player = [[MPMoviePlayerController alloc] init];
[_player.view setFrame:_videoView.bounds];
[_player prepareToPlay];
[_player setShouldAutoplay:NO];
_player.scalingMode = MPMovieScalingModeAspectFit;
_player.controlStyle = MPMovieControlStyleNone;
[_videoView addSubview:_player.view];
//Play Button
_playButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 60.0f, 60.0f)];
[_playButton setBackgroundImage:[UIImage imageNamed:#"play-icon-grey.png"] forState:UIControlStateNormal];
[_playButton addTarget:self.view.superview action:#selector(postThread:) forControlEvents:UIControlEventTouchUpInside];
_playButton.center = CGPointMake(100, 160);
_playButton.tag = 3;
[view addSubview:_playButton];
}
else
{
//get a reference to the label in the recycled view
_playButton = (UIButton *) [view viewWithTag:3];
_videoView = (UIView *) [view viewWithTag:7];
}
//Setting Video For Each Carousel
for (int i = 0; i < 9; i++) {
[_player setContentURL:[NSURL URLWithString:[_videoURLS objectAtIndex:index]]];
NSLog(#"Object Link: %#",[_videoURLS objectAtIndex:index]);
}
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(didFinishPlaying:) name:MPMoviePlayerPlaybackDidFinishNotification object:_player];
return view;
}
It works very well if i have one object in the carousel and can handle just one video, i have to be able to handle 10 videos on the carousel and if possible have them load when its focused.
From Personal experience i feel it would be the way each item is being drawn to the screen, i just cant get my finger on the issue.
Any help is greatly appreciated!!
Per the apple documentation I found out this is not capable of being done, I have chose to use the AVFoundation Framework

How to toggle a sound on/off

i created a sound in DetailViewController,
soundFileURL = [[NSBundle mainBundle] URLForResource:#"click" withExtension:#"wav"];
s1Player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
s1Player.delegate = self;
s1Player.volume = 2;
[s1Player play];
i want to control the above sound in my ViewController. i created a button in ViewController, and toggle it (sound on / off).
i tried,
DetailViewController.m
ViewController *viewController = [[ViewController alloc] init];
if(viewController.stopSound) {
[s1Player stop];
s1Player.volume = 0;
}
else {
[s1Player play];
s1Player.volume = 2;
}
ViewController.h
#property BOOL stopSound;
in ViewController.m
- (void) setSoundAction {
if(_stopSound){
_stopSound = NO;
}
else{
_stopSound = YES;
}
}
If the above code is not understandable or not cleared please suggest me how to toggle a button i.e, sound on and sound off on DetailViewController. Because Sound placed on DetailViewController.
What you want is just toggle button, then how about this?
-(void)viewDidLoad
{
[super viewDidLoad];
UIButton *toggleButton = [UIButton buttonWithType:UIButtonTypeCustom];
toggleButton.frame = CGRectMake(10.0, 10.0, 40.0, 40.0);
[toggleButton setTitle:#"Toggle" forState:UIControlStateNormal];
[toggleButton addTarget:self action:#selector(toggleSound:) forControlEvents:UIControlEventTouchUpInside]; //execute the method when touched
[self.view addSubview:toggleButton];
}
- (void)toggleSound:(UIButton *)btn
{
static BOOL muted; //remember the current status of AVAudioPlayer object.
muted = !muted; //toggle!!
if(muted) {
s1player.volume = 0.0;
} else {
s2player.volume = 1.0; //max value for volume is 1.0
}
}

Mpmovieplayercontroller video pause while clicking button for another functionality

i am using MPMovieplayerController for playing video, while im clicking some other button i.e i want to pause my video wherever its playing again. i click play means i want to play while its pausing.But for me now when i click button means my video was stopped.But i want to pause instead of stop.
My sample code here
- (IBAction) playvideo
{
NSURL *url = [NSURL URLWithString:#"http://xyz/video1.mp4"];
movieplayer = [[[MPMoviePlayerController alloc]initWithContentURL:url] retain];
movieplayer.view.frame=CGRectMake(25,54,658,460);
[self.view addSubview:movieplayer.view];
[movieplayer play];
}
-(void)buttononclick
{
[movieplayer pause];
[movieplayer.view removeFromSuperview];
for (int i = 0; i < 13; i++)
{
CGRect frame;
frame.origin.x = 150 * i;
frame.origin.y = 0;
frame.size = CGSizeMake(140, self.scrollView.frame.size.height);
[scrollView setShowsHorizontalScrollIndicator:NO];
UIImageView *temp1 = [[UIImageView alloc] initWithFrame:CGRectMake(25, 7, 75, 75)];
[temp1 setImage:[UIImage imageNamed:#"sti15.png"]];
[self.scrollView addSubview:temp1];
UIImageView *temp2 = [[UIImageView alloc] initWithFrame:CGRectMake(110, 7, 75, 75)];
[temp2 setImage:[UIImage imageNamed:#"sti16.png"]];
[self.scrollView addSubview:temp2];
UIImageView *temp3 = [[UIImageView alloc] initWithFrame:CGRectMake(195, 7, 75, 75)];
[temp3 setImage:[UIImage imageNamed:#"sti17.png"]];
[self.scrollView addSubview:temp3];
}
self.scrollView.contentSize = CGSizeMake(165 * 10, self.scrollView.frame.size.height);
self.scrollView.pagingEnabled=0;
}
- (void)viewDidDisappear:(BOOL)animated
{
// [self setDescText:nil];
[super viewDidDisappear:animated];
[movieplayer pause];
[movieplayer.view removeFromSuperview];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
if ((movie.playbackState==MPMoviePlaybackStateStopped)||(movie.playbackState==MPMoviePlaybackStatePaused))
{
[movie play];
}
else
{
[movie pause];
}
}
Try this Code , it will Work
Check out the notifications for MPMoviePlaybackStatePlaying, MPMoviePlaybackStateStopped, MPMoviePlaybackStatePaused, and MPMoviePlaybackStateInterrupted.
Something like:
MPMoviePlayerController *player = notification.object;
/* Playback is currently stopped. */
if (player.playbackState == MPMoviePlaybackStateStopped)
{
NSLog(#"MPMoviePlaybackStateStopped");
}
/* Playback is currently under way. */
else if (player.playbackState == MPMoviePlaybackStatePlaying)
{
NSLog(#"MPMoviePlaybackStatePlaying");
}
/* Playback is currently paused. */
else if (player.playbackState == MPMoviePlaybackStatePaused)
{
NSLog(#"MPMoviePlaybackStatePaused");
}
You can wire up your target action something like this:
if ((_moviePlayer.playbackState == MPMoviePlaybackStateStopped) || (_moviePlayer.playbackState == MPMoviePlaybackStatePaused)) {
[_moviePlayer play];
} else {
[_moviePlayer pause];
}
you can add target to the play/pause button.
but first you need to catch the button of the mpmovieplayerview.
step 1 list the button. method reference from here
call this method from when the button appear(the video is ready).
But remember, this will also catch the full screen button and airplay button.(if available)
- (void)CatchSubviewsOfView:(UIView *)view {
// Get the subviews of the view
NSArray *subviews = [view subviews];
for (UIView *subview in subviews) {
// Do what you want to do with the subview
NSLog(#"%#", subview);
if(subview isKindOfClass:[UIButton class]]){
// add your target here
[subview addTarget:self action:#selector(extraAction:) forControlEvents:UIControlEventTouchUpInside];
}
// List the subviews of subview
[self listSubviewsOfView:subview];
}
}
step 2 implement the action
-(IBAction)extraAction:(id)sender{
NSLog(#"some extraAction");
}
call the catch method sample.
[self CatchSubviewOfView:movieplayer.view];

Resources