IOS development: package AVPlayer video playback, one line of code, simple and convenient

One line of code to play video

Encapsulate AVPlayer for video playback, the source code can be modified according to different needs, easy to understand and easy to use

Here is the code introduction:
I created a class of UIView and created an instance method in the class
/**
 Add video view

 @param frame view size position
 @param url video web link
 @param block returns AVPlayer, used to pause, play, get playback progress, and adjust playback progress
 In the block, you need to actively open AVPlayer playback
 */
-(void)addVideoWithPlayerLayerFrame:(CGRect)frame withPlayerItemUrlString:(NSString *)url complete:(void(^)(AVPlayer *player))block;
Because the parent class of each view is UIView, this instance method can be used in every view object (such as UIImageView, UITableViewCell and other parent classes are UIView, so this instance method can be used)
Give it a frame and url to play the video
I also created a UIView with AVPlayer-related controls in it. I made this UIView a singleton. If you need to change the background image or background color of the view outside the playback interface, you can call the singleton method to get the UIVIew object for operation.

Use Cases

Add http protocol in info.plist

import header file

#import "UIView+addVideoToView.h"

Create a global AVPlayer to control video playback pause and progress management

@property(nonatomic,strong)AVPlayer *player;

First initialize a View

UIView *view = [[UIView alloc]initWithFrame:self.view.frame];
[self.view addSubview:view];

Call the instance method and assign the AVPlayer pointer in the Block to the global AVPlayer just created

[view addVideoWithPlayerLayerFrame: video size withPlayerItemUrlString:@"video link" complete:^(AVPlayer *player) {
     _player = player;
 }];

The video is ready, it just hasn't started playing yet.

AVPlayer simple operation:

// Start playing
[_player play];
// Pause video playback
[_player pause];
// Get the total duration of the current video
CGFloat duration = CMTimeGetSeconds(_player.currentItem.duration);
// Get the current playback duration of the current video
CGFloat current = CMTimeGetSeconds(_player.currentItem.currentTime);
// Adjust the current progress of the video CMTimeMake (how long to play, the speed ratio of video playback);
CMTime time = CMTimeMake(100, 1);
[_player seekToTime:time];
// Adjust the playback speed ratio
[_player setRate:1.0];


I also wrote a small Demo about my packaged AVPlayer, which contains my packaged AVPlayer. Interested partners can download it and take a look. I believe everyone will like it very much.

https://pan.baidu.com/s/1r96YtYGpFT20yGpplVmBQA


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324574817&siteId=291194637