How to show buffered data on UISlider using MpMoviePlayerController in iOS? - ios

I am using MPMoviePlayerController to play audio and I want to show the buffered data on slider like this ...
I want to show the buffer data like red section in slider. I have tried to google it. But I didn't get any solution for it.
and How to make slider customize?
Thanks in advance...

Yes We can Show stream data using MPMoviePlayerController by its playableDuration. I am explaining all these steps involved me to make this custom_slider for my customize player...
(You Can direct read step 4 if you only interested in programming part)
These are the steps:
Step 1: (First Design part) i done it using standard Controls...
In Interface Builder place your UISlider immediately on top of your UIProgressView and make them the same size.
On a UISlider the background horizontal line is called the track, the trick is to make it invisible. We do this with a transparent PNG and the UISlider methods setMinimumTrackImage:forState: and setMaximumTrackImage:forState:.
In the viewDidLoad method of your view controller add:
[ProgressSlider setMinimumTrackImage:minImage forState:UIControlStateNormal];
[ProgressSlider setMaximumTrackImage:transparentImage forState:UIControlStateNormal];
[progressBar setTrackImage:maxImage];
[progressBar setProgressImage:streamImage];
where ProgressSlider refers to your UISlider and progressBar to your UIProgressView.
and you can make transparent image programmatically like this.
UIGraphicsBeginImageContextWithOptions((CGSize){512,5}, NO, 0.0f);
UIImage *transparentImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext();
you can change the size of it according to your progress view track image height width... I use {512,5} you can use {1,1} for default slider and progress view.
Reference taken form this answer https://stackoverflow.com/a/4570100/3933302
Step 2:
Now I tried to set the track and progress image of UIProgressView. But it was not showing the track and progress image. then i found this solution...to use this library available in github. https://gist.github.com/JohnEstropia/9482567
Now I changed occurrences of UIProgressView to JEProgressView, including those in NIBs and storyboards.
Basically, you'd need to force assigning the images directly to the UIProgressView's children UIImageViews.
The subclass is needed to override layoutSubviews, where you adjust the heights of the imageViews according to the image sizes.
Reference taken from this Answer https://stackoverflow.com/a/22322367/3933302
Step 3:
But now the question is from which will you make the image for slider and progressView. This is explained in this tutorial and You can download the psd also.
http://www.raywenderlich.com/32167/photoshop-tutorial-for-developers-creating-a-custom-uislider
Step 4:
Now come to programming part..
by using the playable duration it is possible to show stream data..(which was my biggest problem)
Using MPMovieLoadStatePlayable we can get when The buffer has enough data that playback can begin, but it may run out of data before playback finishes.
https://developer.apple.com/library/ios/documentation/MediaPlayer/Reference/MPMoviePlayerController_Class/index.html#//apple_ref/c/tdef/MPMovieLoadState
Now in your PlayAudio method...place this code..
-(void) playAudio:(NSURL *) url {
.............
streamTimer= [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:#selector(loadStateChange) userInfo:nil repeats:YES];
..........
}
and here is the definition of loadStateChange
-(void)loadStateChange
{
if(self.moviePlayer.loadState == MPMovieLoadStatePlayable){
[self.moviePlayer play];
slideTimer = [NSTimer scheduledTimerWithTimeInterval:0.5
target:self
selector:#selector(updateProgressUI)
userInfo:nil
repeats:YES];
[streamTimer invalidate];
}
else if(self.downloadList)
//if you are playing local file then it will show track with full red color
progressBar.progress= appDel.moviePlayerController.moviePlayer.duration;
}
and here is the definition of updateProgressUI
- (void)updateProgressUI{
if(self.moviePlayer.duration == self.moviePlayer.playableDuration){
// all done
[slideTimer invalidate];
}
progressBar.progress = self.moviePlayer.playableDuration/self.moviePlayer.duration ;
}
I hope this fully customize slider will help you lot in making custom player...I explained all my work in steps.....Thanks ....

You cannot do this with MPMoviePlayerController.
However if you switch to AVPlayer then you can use AVPlayerItem.loadedTimeRanges. It contains all information you need for visualization in your custom control.
There are number of questions that have been asked on that topic, for example:
AVPlayer streaming progress

According the documentation of MPMoviePlayerController (available here) you can use the playableDuration property to retrieve the duration that has been loaded by the player.
You would then have to subclass UISlider to draw the red part of your control in the drawRect: method.
As for AVPlayer you would call loadedTimeRanges (documentation here) on the AVPlayerItem representing your content. That would give you an array of (as of iOS 8) a single CMTimeRange representing the part of your media that has been buffered. I would advise using [NSArray firstObject] when retrieving the time range to protect your code against a possibly empty array.

Related

NSTimer not passing parameters correctly?

I have a UITableViewCell. It has 2 AVPlayers, 2 AVPlayerItems, and 2 AVPlayerLayers. One AVPlayer and its contents are on the right side of the cell, and one on the left side of the cell. I am using the AVAssetResourceLoader to cache and play videos at the same time. This works great, except the second video does not display. It does cache properly, because after scrolling the tableview, it plays correctly as it should from the cache. But just the AVPlayerLayer does not display the video content as it should.
The AVAssetResourceLoader can not handle 2 simultaneous downloads. Upon first loading the tableview, the video on the left starts to download/play. The code for playing the video on the right side is read immediately after the code for downloading/playing the video on the left side--meaning of course, that the download process has not yet finished. To fix this problem, I have created a timer, like so:
if (self.downloadInProgress) {
// download is in progress. wait to start next download
self.downloadQueueCount++;
NSDictionary *videoSettings = #{#"id": activity2.objectId,
#"activity": activity2, #"cell": videoCell, #"left": #NO}
self.timer = [NSTimer scheduledTimerWithTimeInterval:0.2
target:self selector:#selector(DownloadNextVideo:)
userInfo:videoSettings repeats:YES];
} else {
[self playStreamingVideoOnRightInCell:videoCell withActivity:activity2];
}
And then the selector method:
- (void)DownloadNextVideo:(NSTimer *)timer {
if (self.downloadInProgress == NO) {
NSString *activityId = [[timer userInfo] objectForKey:#"id"];
self.videoChallengeID1 = activityId;
CompletedTableViewCell *videoCell = (CompletedTableViewCell *)[[timer userInfo]objectForKey:#"cell"];
Activity *activity = [[timer userInfo] objectForKey:#"activity"];
BOOL left = [[timer userInfo] objectForKey:#"left"];
[self.timer invalidate];
if (left) {
[self playStreamingVideoOnLeftInCell:videoCell withActivity:activity];
} else {
[self playStreamingVideoOnRightInCell:videoCell withActivity:activity];
}
}
}
Basically, this works correctly--the AVAssetResourceLoader gets the correct URL, correct activityID, and downloads/caches the correct video--except the video does not play as it downloads. I changed background colors, and I can confirm that the AVPlayerLayer is indeed present in the frame it should be. Just no video shows up.
I tried switching left and right videos and download order--and in that case, the right video played, and the left video didn't play. Basically, whichever video has to use this timer and continually check if a download is in progress or not, is the video that does not display correctly, and that makes me think it is something I am doing wrong with the timer concerning scope/passing variables.
One last detail, in case it may help. If I say the following (instead of the first method I had here):
if (self.downloadInProgress) {
[self playStreamingVideoOnRightInCell:videoCell withActivity:activity2];
}
Then, the playerLayer DOES show video--but it's the wrong video. It shows the same video as in the left side of the cell.
This has been a nightmare to debug, and I am fairly certain at this point that it has something to do with using a timer here to play the video instead of doing it inside the regular scope. Anyone have any ideas what I could be doing wrong?
In order to fix the proper video playing, you need to change the following. You are using the NSNumber value instead of a BOOL for the left value.
Your code:
BOOL left = [[timer userInfo] objectForKey:#"left"];
Should be:
BOOL left = [[[timer userInfo] objectForKey:#"left"] boolValue];

AppleWatch circle progress (or radial arc progress) with images error

I'm developing an app for Apple Watch using WatchKit and I need to implement a circular progress while recording audio, similar to Apple demos.
I don't know if WatchKit includes something to do it by default so I have created my own images (13 for 12 seconds [209 KB in total]) that I change with a timer.
This is my source code:
Button action to start/stop recording
- (IBAction)recordAction {
NSLogPageSize();
NSLog(#"Recording...");
if (!isRecording) {
NSLog(#"Start!");
isRecording = YES;
_timerStop = [NSTimer scheduledTimerWithTimeInterval:12.0
target:self
selector:#selector(timerDone)
userInfo:nil
repeats:NO];
_timerProgress = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:#selector(progressChange)
userInfo:nil
repeats:YES];
} else {
NSLog(#"Stop :(");
[self timerDone];
}
}
Action when timer is finished or if tap again on the button
-(void) timerDone{
NSLog(#"timerDone");
[_timerProgress invalidate];
_timerProgress = nil;
[recordButtonBackground setBackgroundImageNamed:[NSString stringWithFormat:#"ic_playing_elipse_12_%d", 12]];
counter = 0;
isRecording = NO;
}
Method to change progress
- (void)progressChange
{
counter++;
NSLog(#"%d", counter);
NSString *image = [NSString stringWithFormat:#"ic_playing_elipse_12_%d", counter];
[recordButtonBackground setBackgroundImageNamed:image];
NSLog(image);
}
This is a gif showing the bug. It starts to show but change the image randomly until it gets a pair of seconds. (Note: I have already checked that the first images have the right progress)
Update (other solution): using startAnimating
There is a new way to show a circle progress using startAnimatingWithImagesInRange:duration:repeatCount
You need to specify the images range and the duration for your animation. See an example below:
[self.myElement startAnimatingWithImagesInRange:NSMakeRange(0, 360) duration:myDuration repeatCount:1];
I believe this is a side-effect of the way WatchKit interprets image names.
Image names ending in numbers are used to represent frames in an animated image, so "ic_playing_elipse_12_10" is being interpreted as the first frame of the image named "ic_playing_eclipse_12_1" and your 10th image gets displayed when you want it to display your first one.
You should be able to just change your image names so the number isn't the last part of the image name and it will fix it.
I know that this question is answered but I would like to explain better the solution of startAnimating.
[myElement startAnimatingWithImagesInRange:NSMakeRange(imageIdBegin, imageIdEnd) duration:duration repeatCount:repetitions];
In order to use this, you need a suite of images named like you want but with sequential ids. For example: progress_0.png, progress_1.png, progress_2.png, .., progress_n.png
You can decide the begin index and the end index using that values in NSMakeRange(imageIdBegin, imageIdEnd) just indicating the number id (not the full image name)
Of course, you will need to indicate the duration of the animation in seconds, WatchKit will interpolate for you to animate your images between init index and end index.
And finally, you can indicate if you want to repeat this animation (for example for a loading action) or not. If you don't want to repeat, you have to indicate 1.
I hope this can help more people to perform circle progress or another animations inside their AppleWatch applications :)

How to display images in array, pause between each image? [duplicate]

This question already has answers here:
Calling sleep(5); and updating text field not working
(4 answers)
Closed 8 years ago.
In my Application, I have a NSMutableArray with UIImage in it.
I would like to display the first UIImage in the array for three seconds, and then to
display the second image.
All of this should happen when I press a UIButton.
Below is my code:
[testImageView setImage:[arr objectAtIndex:0]] ;
sleep(3) ;
[testImageView setImage:[arr objectAtIndex:1]] ;
testImageView is a UIImageView object on my screen.
When I'm running this code, my button remain pressed for three seconds and only the second image is displayed.
What should I do?
Try using one of the most obscure methods of UIImageView.
UIImageView *myImageView = [[UIImageView alloc] initWithFrame:...];
myImageView.animationImages = images;
myImageView.animationDuration = 3.0 * images.count;
[self.view addSubview:myImageView];
Then, when you wanna start animating
[myImageView startAnimating];
I don't know what you plan on doing with this, but 3 seconds might be too much. If you're doing some sort of presentation-ish, then this method might not be very good, since there's no easy way of going back.
The reason that your button remains pressed is because you slept main thread for 3 seconds, this means that nothing is going to happen to your application (at least the user interface) until thread is back to active.
There are multiple ways to achieve what you wish, but you must put a timer on the background thread. I would suggest you put the code to set the second image in another method first and make array into a property.
- (void)setImage
{
[testImageView setImage:self.yourArray[1]];
}
Then you can use one of the following ways to execute the method:
Use a NSTimer:
[NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:#selector(setImage) userInfo:nil repeats:NO]
Use performSelector method of NSObject:
[self performSelector:#selector(setImage) withObject:nil afterDelay:3.0];
Use Grand Central Dispatch.
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 3.0), dispatch_get_main_queue(), ^{
[self setImage];
});
Any of the ways described above will work.
Read more information about concurrency on the links below:
http://jeffreysambells.com/2013/03/01/asynchronous-operations-in-ios-with-grand-central-dispatchNS
https://developer.apple.com/library/ios/documentation/general/conceptual/concurrencyprogrammingguide/Introduction/Introduction.html
how to call a method of multiple arguments with delay
How can I delay a method call for 1 second?

UIImageView+animatedGIF always LOOPS

I used class made by "mayoff" (Rob Mayoff) "UIImageView+animatedGIF" which was proposed in one of the answers here on stackoverflow. UIImageView+animatedGIF
With it I can import animated .gif images in UIImageView on iOS. This class works flawlessly, but the only problem is that .gif is always looping. No matter how I export it (I am exporting image from photoshop - 67 frames, set repeat to "once") it loops forever in UIImageView.
I am importing my .gif with these two lines:
NSURL *url = [[NSBundle mainBundle] URLForResource:#"Loading" withExtension:#"gif"];
self.loadingImageView.image = [UIImage animatedImageWithAnimatedGIFData:[NSData dataWithContentsOfURL:url]];
very simple and it works.
I have tried setting animationRepeatCount property to 1, as recomended by Rob but that didn't do the trick. Also I have tried setting the UIImageView's animationImages property to
gifImage.images too, instead of just setting the view's image property
to gifImage. In that case, .gif is not animating at all.
Any ideas how to play that .gif only once? I can think of many tricks (like setting last frame of the gif to show up after some time but I'd first try something simpler if possible).
I took the test app from that project and changed the viewDidLoad method to this:
- (void)viewDidLoad {
[super viewDidLoad];
NSURL *url = [[NSBundle mainBundle] URLForResource:#"test" withExtension:#"gif"];
UIImage *testImage = [UIImage animatedImageWithAnimatedGIFData:[NSData dataWithContentsOfURL:url]];
self.dataImageView.animationImages = testImage.images;
self.dataImageView.animationDuration = testImage.duration;
self.dataImageView.animationRepeatCount = 1;
self.dataImageView.image = testImage.images.lastObject;
[self.dataImageView startAnimating];
}
When the app launches, it animates the image once and then shows just the last frame. If I connect a button that sends [self.dataImageView startAnimating], then tapping the button runs the animation one more time, then stops again on the last frame.
Make sure you're setting your image view up the way I do above. Make sure you are not setting the image view's image property to the animated image. The image view's image property must be set to a non-animated image if you want the animation to stop.
I have forked "uiimage-from-animated-gif" made by "Dreddik" and added a delegate method
#pragma mark - AnimatedGifDelegate
- (void)animationWillRepeat:(AnimatedGif *)animatedGif
{
NSLog(#"animationWillRepeat");
//[animatedGif stop];
}
So you know the time when animation will repeat and do your own thing in middle of every repetition. You may count the number of times animation repeated and stop animation at a certain number reached.
The forked repository is at https://github.com/rishi420/Animated-GIF-iPhone
Was having issues in start/stp animation & managing animation count
So used this pod
imageViewObject.animate(withGIFNamed: "gif_name", loopCount: 1) {
print("animating image")
}
To start/stop animation :
imageViewObject.isAnimatingGIF ? imageViewObject.stopAnimatingGIF() : imageViewObject.startAnimatingGIF()

NSTIMER seems to be ignored

I have created a program and found an error that i cannot seem to work out.
I have stripped the problem out to recreate in a brand new project but it still re occurs.
The problem is when i press the BUTTON the image changes but at a much faster speed than the speed set up in NSTIMER but only the first time the button is pressed.
If i carry on pressing the button the image changes at the speed i require.
IT ONLY HAPPENS ON THE FIRST TIME ROUND AND I AM USING A TOUCH DOWN EVENT ( ALTHOUGH I HAVE TRIED TOUCH UP INSIDE )
This only happens the first time and is extremely important that the first time is the same timing as the rest.
I am aware of various discussions as to the accuracy of NSTIMER anyway , but i dont think it is relevant to my question
here is my .h
- (IBAction)slap:(id)sender {
NSString *imagechange4 = [NSString stringWithFormat:#"onehandedplayer2.png"];
//player2 is an UIButton IBOutlet
[player2 setImage:[UIImage imageNamed:imagechange4]];
[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:#selector(handsback1) userInfo:nil repeats:NO];
}
-(void)handsback1 {
NSString *imagechange3= [NSString stringWithFormat:#"hands rotated.png"];
[player2 setImage:[UIImage imageNamed:imagechange3]];
}
Try using performSelector -
[self performSelector:#selector(handsback1) withObject:nil afterDelay:0.5];
It's really easy & reliable.
Just had an idle couple of minutes (!) & came across this again - it occurred to me that you could be mistaking the button highlighting when pressed as the image change - have you unchecked the button's "Highlighted Adjusts Image" property in IB's Attributes Inspector?
Unlikely perhaps, but you never know...

Resources