iphone MPMoviePlayerViewController : extract total duration - iphone

how can i get the video'a total time, before it plays the video in MPMoviePlayerViewController?

To get total duration of movie you can use :
1). Use AVPlayerItem class and AVFoundation and CoreMedia framework. (I have used UIImagePickerController for picking the movie)
#import <AVFoundation/AVFoundation.h>
#import <AVFoundation/AVAsset.h>
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
selectedVideoUrl = [info objectForKey:UIImagePickerControllerMediaURL];
AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:selectedVideoUrl];
CMTime duration = playerItem.duration;
float seconds = CMTimeGetSeconds(duration);
NSLog(#"duration: %.2f", seconds);
}
2). MPMoviePlayerController has a property duration .Refer Apple Doc

To get the total Duration in MPMoviePlayerViewController
MPMoviePlayerViewController *mp;
float seconds =mp.moviePlayer.duration;
Note: Above code give the total Duration of related Media in seconds

If you don't want to get the total time from MPMoviePlayerViewController's duration property (because that brings up the movie player UI), you could instead create an AVAsset object with your video file passed in via a file URL and then check the duration property on that.
This trick would only work on iOS 5 (which is where AVAsset's assetWithURL: came in with).

YOu can get using this method in swift
func getMediaDuration(url: NSURL!) -> Float64{
var asset : AVURLAsset = AVURLAsset.assetWithURL(url) as AVURLAsset
var duration : CMTime = asset.duration
return CMTimeGetSeconds(duration)
}

Related

Audio player duration changes while playing

When I take the duration of an audio file before playing it with:
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
...
[audioPlayer prepareToPlay];
duration = audioPlayer.duration;
I get a duration of for example 16.71s. Then when taking samples every 0.2s while playing, the duration changes. It changes every 1.2 to 1.6 seconds to: 16.71s, 17.02s, 17.23s, 17.33s, 17.38s, 17.43s, 17.38s, 17.29s, 17.31s, then stays at 17.51s for the last 2.5 seconds. So it goes up and down.
I sample in a method that updates a slider position, and also shows the elapsed time and total duration. You can imagine it looks really weird to see the duration (which is int-truncated) go from 16 to 17 while playing. Additionally, the slider position will be off with all this drifting.
Does anyone have an idea why this is?
Now that we're talking about duration: Does anyone know why audio player.duration can return values that are about twice the actual duration when [audioPlayer prepareToPlay] is omitted?
The duration returned by avaudioplayer's duration method is a best estimate of the total duration of the file based on how much of the file has been decoded so far. That's why the duration continues to get refined as you check it over time.
In order to get a better time, I use AVAsset's duration method. It explains what is going on a bit better here:
https://developer.apple.com/library/mac/documentation/AVFoundation/Reference/AVAsset_Class/Reference/Reference.html#//apple_ref/occ/instp/AVAsset/duration
If you specify providesPreciseDurationAndTiming = YES, then AVAsset will decode the file if needed to determine its duration with accuracy. If the decode time is too long for your use, you can disable it.
In my situation, I use the AVURLAsset subclass:
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:localURL options:[NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithBool:YES], AVURLAssetPreferPreciseDurationAndTimingKey, nil]];
float t = CMTimeGetSeconds(asset.duration);
#AndyKorth's answer is the best! Here it is in Swift
guard let audioPlayer = audioPlayer, let url = audioPlayer.url else { return }
let assetOpts = [AVURLAssetPreferPreciseDurationAndTimingKey: true]
let asset = AVURLAsset(url: url, options: assetOpts)
let assetDuration: Float64 = CMTimeGetSeconds(asset.duration)
// compare both
print("assetDuration: ", assetDuration)
print("audioPlayerDuration: ", Float(audioPlayer.duration))

AVPlayer currently playing item details and volume control in iPhone?

I have tried AVPlayer for playing online http streamed music file, it works fine.
What is the way to get the current playing audio track name,artist etc?
Is there any way to adjust the volume of AVPlayer while playing music (using UISlider)?
You can adjust the volume by:
player.volume = slider.value;
MPMediaItem *currentItem = self.musicPlayer.nowPlayingItem;
//Display the artist, album, and song name for the now-playing media item.
//These are all UILabels.
self.songLabel.text = [currentItem valueForProperty:MPMediaItemPropertyTitle];
self.artistLabel.text = [currentItem valueForProperty:MPMediaItemPropertyArtist];
self.albumLabel.text = [currentItem valueForProperty:MPMediaItemPropertyAlbumTitle];

AVPlayer current time is not working

OK. AvPlayer is working great with streaming audio. In my app I have UISlider that shows current seconds of the playing song. Now I'm trying to make audio seek with UISlider.
Here is the code
-(IBAction)slide{
Float64 curSec = mySlider.value;
int32_t tScale = 600;
CMTime mySec = CMTimeMakeWithSeconds(curSec, tScale);
player.currentTime = mySec; <- error is here
NSLog(#"%f",mySlider.value);
}
The error is "Setter method is needed to assign to object using property assignment syntax"
In .h file I have AVPlayer *player; and #property(nonatomic, retain)AVPlayer *player. Also in .m I have #synthesize player;
So what is wrong? THANK YOU!
According to the doc, it seems to me that you have to use seekToTime: method instead of setting time directly to the currentTime property.
float second = 30.0;
CMTime time = CMTimeMake(second, 1);
[player seekToTime:time];

How to play a segment of a movie in iOS

I have a video, and I want to display the video at a specific time time and stop it at a specific time. I am using MPMoviePlayerController.
You should take a look at the MPMoviePlayerController Class Reference, and the initialPlaybackTime and endPlaybackTime properties.
MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL:url];
player.initialPlaybackTime = 5; // beginning time in seconds
player.endPlaybackTime = 15; // end time for playback in seconds

How to get file size and current file size from NSURL for AVPlayer iOS4.0

self.player = [[AVPlayer playerWithURL:[NSURL URLWithString:#"http://myurl.com/track.mp3"]] retain];
I am trying make a UIProgressView for the above track. How do I obtain the file size and current file size from that URL? Please help, thanks!
You need to start observing the loadedTimeRanges property of the current item, like this:
AVPlayerItem* playerItem = self.player.currentItem;
[playerItem addObserver:self forKeyPath:kLoadedTimeRanges options:NSKeyValueObservingOptionNew context:playerItemTimeRangesObservationContext];
Then, in the observation callback, you make sense of the data you're passed like this:
-(void)observeValueForKeyPath:(NSString*)aPath ofObject:(id)anObject change:(NSDictionary*)aChange context:(void*)aContext {
if (aContext == playerItemTimeRangesObservationContext) {
AVPlayerItem* playerItem = (AVPlayerItem*)anObject;
NSArray* times = playerItem.loadedTimeRanges;
// there is only ever one NSValue in the array
NSValue* value = [times objectAtIndex:0];
CMTimeRange range;
[value getValue:&range];
float start = CMTimeGetSeconds(range.start);
float duration = CMTimeGetSeconds(range.duration);
_videoAvailable = start + duration; // this is a float property of my VC
[self performSelectorOnMainThread:#selector(updateVideoAvailable) withObject:nil waitUntilDone:NO];
}
Then the selector on the main thread updates a progress bar, like so:
-(void)updateVideoAvailable {
CMTime playerDuration = [self playerItemDuration];
double duration = CMTimeGetSeconds(playerDuration);
_videoAvailableBar.progress = _videoAvailable/duration;// this is a UIProgressView
}
I think you do not want to know anything about file-sizes, but you're more interested in times.
Try self.player.currentItem.asset.duration for duration of currently playing item, self.player.currentTime for current time.
#"loadedTimeRange" is a KVO value for the AVPlayerItem class. You can find its definition in the AVPlayerItem.h file in the
#interface AVPlayerItem (AVPlayerItemPlayability)
category definition.