Basic use of AVPlayer

Source: Internet
Author: User

In iOS development, you can play a video in either of the following ways: MPMoviePlayerController (you need to import MediaPlayer. Framework) or AVPlayer. For the differences between the two classes, refer to examples. This blog mainly introduces the basic use of AVPlayer. As the blogger has just been in touch, you can directly point out some problems ~

In development, videos cannot be displayed simply by using the AVPlayer class. You must add the video layer to the AVPlayerLayer to display the video, therefore, add the following attributes in @ interface of ViewController:

@property (nonatomic ,strong) AVPlayer **playerItem;
@property (nonatomic ,weak) IBOutletPlayerView *playerView;

PlayerView inherits from UIView, but the set and get methods are rewritten to add the player to the AVPlayerLayer of playerView so that the video can be displayed smoothly.

In PlayerView. h. Declare An AVPlayer object. Because the default layer is CALayer, and AVPlayer can only be added to AVPlayerLayer, change the layerClass so that the default layer of PlayerView is changed, then, we can assign the AVPlayer object initialized in viewController to the player attribute of AVPlayerLayer.

PlayerView. h

@ Property (nonatomic, strong) AVPlayer * player;

 

PlayerView. m

+ [AVPlayerLayer - (AVPlayer * [(AVPlayerLayer *- ()setPlayer:(AVPlayer **

Then execute initialization in viewDidLoad:

NSURL *videoUrl = [NSURL URLWithString:= options:NSKeyValueObservingOptionNew context:nil];[self.playerItem addObserver:self forKeyPath: options:NSKeyValueObservingOptionNew context:nil];self.player = [AVPlayer playerWithPlayerItem:self.playerItem];
[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(moviePlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotificationobject:self.playerItem];

First, store the online video link in videoUrl, and then initialize playerItem. playerItem is the object for resource management (A player item manages the presentation state of an asset with which it is associated. A player item contains player item tracks-instancesAVPlayerItemTrack-That correspond to the tracks in the asset .)

Then listen to the status and loadedTimeRange attributes of playerItem. There are three statuses of status:

AVPlayerStatusUnknown,

AVPlayerStatusReadyToPlay,

AVPlayerStatusFailed

When status is equal to AVPlayerStatusReadyToPlay, you can call the play method to play the video.

The loadedTimeRange attribute indicates the buffer progress. Listening to this attribute can update the buffer progress in the UI, which is also a useful attribute.

Add a notification to monitor whether the video has been played and then implement KVO:

- ()observeValueForKeyPath:(NSString *)keyPath ofObject:() change:(NSDictionary *)change context:( **playerItem = (AVPlayerItem *) ([keyPath isEqualToString: ([playerItem status] ==== self.playerItem.duration;            CGFloat totalSecond = playerItem.duration.value / playerItem.duration.timescale;            _totalTime = [self convertTime:totalSecond];            [self customVideoSlider:duration];            NSLog(        }   ([playerItem status] ==  ([keyPath isEqualToString:= [self availableDuration];        NSLog(==/-*loadedTimeRanges == [loadedTimeRanges.firstObject CMTimeRangeValue];     startSeconds = durationSeconds == startSeconds + durationSeconds;    - (NSString **d =*formatter = (second/ >= *showtimeNew =

This method mainly responds to the status and loadedTimeRanges attributes. When the status changes to AVPlayerStatusReadyToPlay, the video can be played. In this case, we can obtain the video information, including the video length, enabled the play button device and click it to call the play method to play the video. There is a monitoringPlayback method at the bottom of AVPlayerStatusReadyToPlay:

- ()monitoringPlayback:(AVPlayerItem *= [self.playerView.player addPeriodicTimeObserverForInterval:CMTimeMake(, ) queue:NULL usingBlock:^= playerItem.currentTime.value/playerItem.currentTime.timescale;*timeString == [NSString stringWithFormat:

MonitoringPlayback is used to listen to the status every second.-(id) addPeriodicTimeObserverForInterval :( CMTime) interval queue :( dispatch_queue_t) queue usingBlock :( void (^) (CMTime time) block, the interval parameter is the response interval, which is set to respond every second. The queue is a queue, and NULL indicates that the request is executed in the main thread. You can update a UI, such as the current time of the progress bar.

 

As a player, in addition to playing, pausing, and other functions. Another essential feature is to display the current playback progress and buffer area. My idea is to use UIProgressView to display the buffer playable area, use UISlider to display the progress of the video being played. Of course, you need to customize UISlider. The Code is as follows:

- (=,  }, NO, *transparentImage =

In this way, UISlider only has the middle ThumbImage, and the color of ThumbImage becomes transparent, only used to display the current playback time. UIProgressView is used to display the currently buffered area without any custom modifications. It looks like this on the StoryBoard:

Add UISlider to UIProgressView, and the running effect becomes as follows:

In this way, the basic buffer function is ready. Of course, some functions are not available, such as the volume, sliding screen, fast forward, and fast return. You can play with it yourself if you have time ~ The final effect is as follows:

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.