在IOS開發中經常會用到系統相冊,相機,音視頻等功能。每次都寫比較麻煩,自己封裝了一個工具類,實現一句話調用系統相冊,相機,音視頻等功能。方便以后項目的開發。
//選擇圖片
[[OCSystemTool shareTool]choosePicture:self editor:YES finished:^(UIImage * _Nullable image) {
_headerView.image = image;
}];
//視頻:http://baobab.wdjcdn.com/14562919706254.mp4
[[OCSystemTool shareTool]playVideoWithPath:@"apple.mp4" viewController:self];
//音樂
[[OCSystemTool shareTool]playAudioWithPath:@"song.mp3"];
//停止音樂播放
[[OCSystemTool shareTool]stopAudioPlayer];
本文附上OC版代碼:(PS:Swift3.0版見鏈接www.lxweimin.com/p/c8e99bf35970)
.h文字
////? Tool.h//? SystemFunction////? Copyright (c) 2017年 hailong. All rights reserved.//#import#import#import#import@interface Tool : NSObject///<1>定義block
typedef void(^myBlock)(UIImage * _Nullable image);
///<2>聲明屬性
@property (nonatomic, copy) myBlock _Nullable block;
//音頻播放器
@property (nonatomic, strong) AVAudioPlayer * _Nullable audioPlayer;
//帶有視頻播放器的控制器,能夠播放MP4、MOV、avi、以及流媒體m3u8格式的視頻,能夠播放遠程和本地的視頻資源
@property (nonatomic, strong) AVPlayerViewController * _Nullable playerController;
@property (nonatomic, strong) AVPlayer *_Nullable videoPlayer;
//1 返回單例的靜態方法
+(Tool *_Nullable)shareTool;
//2 選擇圖片
- (void)choosePicture:(UIViewController *_Nullable)controller editor:(BOOL)editor finished:(void (^_Nullable)(UIImage * _Nullable image))success;
//3 播放聲音
- (void)playAudioWithPath:(NSString *_Nullable)sound;
//停掉音頻
- (void)stopAudioPlayer;
///4 播放視頻
-(void)playVideoWithPath:(NSString *_Nullable)videoPath viewController:(UIViewController*_Nullable)viewController;
//返回特定尺寸的UImage? ,? image參數為原圖片,size為要設定的圖片大小
-(UIImage*_Nonnull)resizeImageToSize:(CGSize)size
sizeOfImage:(UIImage *_Nullable)image;
//在指定的視圖內進行截屏操作,返回截屏后的圖片
-(UIImage *_Nullable)imageWithScreenContentsInView:(UIView *_Nullable)view;
@end
.m文件
////? Tool.m//? SystemFunction////? Copyright (c) 2017年 hailong. All rights reserved.//#import "Tool.h"#import//里面預置了跟系統設置資源相關的常量和一些參數#import@implementation Tool
static Tool *_shareTool =nil;
///1 返回單例的靜態方法
+(Tool *)shareTool
{
//確保線程安全
@synchronized(self){
//確保只返回一個實例
if (_shareTool == nil) {
_shareTool = [[Tool alloc] init];
}
}
return _shareTool;
}
-(id)init
{
self = [super init];
if (self) {
}
return self;
}
///2 選擇圖片
- (void)choosePicture:(UIViewController *)controller editor:(BOOL)editor finished:(void (^)(UIImage * _Nullable image))success{
///<3>實現block
self.block = success;
UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"請選擇圖片" message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
[alertC addAction:[UIAlertAction actionWithTitle:@"拍照" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
//相機
[self loadImagePickerWithSourceType:UIImagePickerControllerSourceTypeCamera controller:controller editor:editor];
}]];
[alertC addAction:[UIAlertAction actionWithTitle:@"從相冊選取" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
//相冊庫
[self loadImagePickerWithSourceType:UIImagePickerControllerSourceTypePhotoLibrary controller:controller editor:editor];
}]];
[alertC addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
}]];
[controller presentViewController:alertC animated:YES completion:nil];
}
///3 播放聲音
- (void)playAudioWithPath:(NSString *_Nullable)audioPath{
//音頻
NSURL *url;
//https 更安全的http協議
if ([audioPath rangeOfString:@"http://"].location != NSNotFound||[audioPath rangeOfString:@"https://"].location != NSNotFound) {
//遠程的地址
url = [NSURL URLWithString:audioPath];
}else{
//本地的路徑
NSString *localPath = [[NSBundle mainBundle] pathForResource:audioPath ofType:nil];
if (localPath.length==0) {
NSLog(@"沒有讀到資源!");
return;
}
url = [NSURL fileURLWithPath:localPath];
}
if (_audioPlayer) {
_audioPlayer = nil;
}
//AVPlayer
_audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
//設置代理
_audioPlayer.delegate = self;
[_audioPlayer prepareToPlay];//預處理
[_audioPlayer play];//播放
}
//停掉音頻
- (void)stopAudioPlayer{
if (_audioPlayer) {
[_audioPlayer stop];//停止播放
_audioPlayer = nil;
}
}
///4 播放視頻
-(void)playVideoWithPath:(NSString *)videoPath viewController:(UIViewController*)viewController{
NSURL *url;
//https 更安全的http協議
if ([videoPath rangeOfString:@"http://"].location !=NSNotFound||[videoPath rangeOfString:@"https://"].location!=NSNotFound) {
//遠程的地址
url = [NSURL URLWithString:videoPath];
}else{
NSString *localPath = [[NSBundle mainBundle] pathForResource:videoPath ofType:nil];
if (localPath.length==0) {
NSLog(@"沒有找到資源");
return;
}
url = [NSURL fileURLWithPath:localPath];
}
_playerController = [[AVPlayerViewController alloc]init];
_videoPlayer = [[AVPlayer alloc]initWithURL:url];
_playerController.player = _videoPlayer;
/*
可以設置的值及意義如下:
AVLayerVideoGravityResizeAspect? 不進行比例縮放 以寬高中長的一邊充滿為基準
AVLayerVideoGravityResizeAspectFill 不進行比例縮放 以寬高中短的一邊充滿為基準
AVLayerVideoGravityResize? ? 進行縮放充滿屏幕
*/
_playerController.videoGravity = AVLayerVideoGravityResizeAspect;
[viewController presentViewController:_playerController animated:YES completion:^{
[self stopAudioPlayer];//停掉音頻
//播放
[_playerController.player play];
}];
//NSNotificationCenter 通知中心,單例,可以理解為程序中的廣播站
//在通知中心注冊self成為某條廣播的觀察者(具有接收某條廣播能力的一個對象)
//name 廣播的名稱
//作用:一旦有其他對象通過通知中心發送MPMoviePlayerPlaybackDidFinishNotification這條廣播,self就能接收到,進而觸發@selector方法
//涉及到對象一對多的場景(非常重要)
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playFinished) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
//通過通知中心發廣播
//點擊Done按鈕,播放器會自動通過通知中心發送廣播
//[[NSNotificationCenter defaultCenter] postNotificationName:MPMoviePlayerPlaybackDidFinishNotification object:nil];
}
- (void)playFinished{
//通過通知中心注銷(移除)self對廣播的觀察
[[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
if (_playerController) {
[_playerController.player pause];
_playerController = nil;
}
}
#pragma mark - AVAudioPlayerDelegate
//一首歌播放完成后,調用此方法
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
NSLog(@"finshed!");
}
//當操作系統級別的功能介入(短信、電話),播放器被打斷時,調用
- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player{
NSLog(@"begin interruption!");
}
- (void)audioPlayerEndInterruption:(AVAudioPlayer *)player withOptions:(NSUInteger)flags{
if (player) {
[player play];//播放和繼續播放
}
}
#pragma mark - 調用相機和相冊庫資源
- (void)loadImagePickerWithSourceType:(UIImagePickerControllerSourceType)type controller:(UIViewController *)controller editor:(BOOL)editor{
if (![UIImagePickerController isSourceTypeAvailable:type]){
[self showAlertWithMessage:@"相機無法使用" controller:controller];
return;
}
//UIImagePickerController 系統封裝好的加載相機、相冊庫資源的類
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
//加載不同的資源
picker.sourceType =type;
//是否允許picker對圖片資源進行優化
picker.allowsEditing = editor;
picker.delegate = self;
//軟件中習慣通過present的方式,呈現相冊庫
[controller presentViewController:picker animated:YES completion:^{
}];
}
- (void)showAlertWithMessage:(NSString *)message controller:(UIViewController *)controller {
UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"溫馨提示" message:message preferredStyle:(UIAlertControllerStyleAlert)];
[alertC addAction:[UIAlertAction actionWithTitle:@"確定" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
}]];
[controller presentViewController:alertC animated:YES completion:nil];
}
#pragma mark - 在指定的視圖內進行截屏操作,返回截屏后的圖片
-(UIImage *)imageWithScreenContentsInView:(UIView *)view
{
//根據屏幕大小,獲取上下文
UIGraphicsBeginImageContext([[UIScreen mainScreen] bounds].size);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return viewImage;
}
-(UIImage*)resizeImageToSize:(CGSize)size
sizeOfImage:(UIImage*)image
{
UIGraphicsBeginImageContext(size);
//獲取上下文內容
CGContextRef ctx= UIGraphicsGetCurrentContext();
CGContextTranslateCTM(ctx, 0.0, size.height);
CGContextScaleCTM(ctx, 1.0, -1.0);
//重繪image
CGContextDrawImage(ctx,CGRectMake(0.0f, 0.0f, size.width, size.height), image.CGImage);
//根據指定的size大小得到新的image
UIImage* scaled= UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return scaled;
}
#pragma mark - UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
//選擇完照片 或者 照完相之后 ,會調用該方法,并且選擇的圖片或者照出來的圖片都存到了info里面
/*
if (picker.sourceType == UIImagePickerControllerSourceTypePhotoLibrary) {
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
_headerView.image = image;
}else if (picker.sourceType == UIImagePickerControllerSourceTypeCamera){
UIImage *image =[info objectForKey:UIImagePickerControllerEditedImage];
_headerView.image = image;
}*/
//獲取資源的類型(圖片or視頻)
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
//kUTTypeImage 代表圖片資源類型
if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
//直接拿到選中的圖片,
//手機拍出的照片大概在2M左右,拿到程序中對圖片進行頻繁處理之前,需要對圖片進行轉換,否則很容易內存超范圍,程序被操作系統殺掉
UIImage *EditedImage = [info objectForKey:UIImagePickerControllerEditedImage];
UIImage *smallImage = [self resizeImageToSize:CGSizeMake(200,200) sizeOfImage:EditedImage];
///<4>調用block
self.block(smallImage);
}
[picker dismissViewControllerAnimated:YES completion:^{
}];
}
//取消選擇的圖片
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
[picker dismissViewControllerAnimated:YES completion:^{
}];
}
@end
/*
@interface ImageTool()
@end
*/