iOS开发学习之路【高级主题】——多媒体编程

实现播放音乐

in Build Phases -> Link Binary With Libraries, add “AVFoundation.framework”.

在这里插入图片描述

将mp3文件添加到项目文件夹

在这里插入图片描述

在storyboard中加入两个按钮并通过助手编辑区关联

在这里插入图片描述

导入 AVFoundation/AVFoundation.h

#import <AVFoundation/AVFoundation.h>
#import "ViewController.h"

@interface ViewController ()
@property(nonatomic, strong)AVAudioPlayer *player;
@end

@implementation ViewController

-(void)initPlayer{
    NSBundle *b = [NSBundle mainBundle];
    NSString *path = [b pathForResource:@"平凡之路" ofType:@".mp3"];
    NSURL *url = [NSURL fileURLWithPath:path];
    self.player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
}


- (IBAction)stop:(id)sender {
    
    if (self.player != nil) {
        [self.player stop];
    }
    
}
- (IBAction)play:(id)sender {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        if (self.player != nil) {
            [self.player play];
        }
    });
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initPlayer];
    
    // Do any additional setup after loading the view.
}

@end

运行成功~

处理播放中断和续播

继承 AVAudioPlayerDelegate 代理

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
@interface ViewController : UIViewController<AVAudioPlayerDelegate>

@end

实现代理

-(void)initPlayer{
    NSBundle *b = [NSBundle mainBundle];
    NSString *path = [b pathForResource:@"平凡之路" ofType:@".mp3"];
    NSURL *url = [NSURL fileURLWithPath:path];
    self.player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
    
    self.player.delegate = self;
}

- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player NS_DEPRECATED_IOS(2_2, 8_0){
    NSLog(@"audioPlayerBeginInterruption...");
}

/* audioPlayerEndInterruption:withOptions: is called when the audio session interruption has ended and this player had been interrupted while playing. */
/* Currently the only flag is AVAudioSessionInterruptionFlags_ShouldResume. */
- (void)audioPlayerEndInterruption:(AVAudioPlayer *)player withOptions:(NSUInteger)flags NS_DEPRECATED_IOS(6_0, 8_0){
    if(flags == AVAudioSessionInterruptionFlags_ShouldResume){
        [self.player play];
    }
}

实现录音

准备工作

in Build Phases -> Link Binary With Libraries, add "AVFoundation.framework"and ”MediaPlayer.framework“.

设置录音文件保存位置

@property(nonatomic, strong)NSURL *currentURL;

    NSString *tempDir = NSTemporaryDirectory();
    NSString *filePath = [tempDir stringByAppendingString:@"tempRecFile"];
    self.currentURL = [NSURL fileURLWithPath:filePath];

设置 AVAudioSession

	AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
    if (session != nil) {
        [session setActive:YES error:nil];
    }

初始化 AVAudioRecorder 和 AVAudioPlayer

@property(nonatomic, strong)AVAudioRecorder *recorder;
@property(nonatomic, strong)AVAudioPlayer *player;

    self.recorder = [[AVAudioRecorder alloc]initWithURL:self.currentURL settings:nil error:nil];
    self.player = [[AVAudioPlayer alloc]initWithContentsOfURL:self.currentURL error:nil];

实现录音

	[self.recorder prepareToRecord];
    [self.recorder record];

	[self.recorder stop];

播放录音

	[self.player play];

播放视频

准备工作

in Build Phases -> Link Binary With Libraries, add "MediaPlayer.framework“.

实现

#import "MediaPlayer/MediaPlayer.h"

@interface ViewController : UIViewController<MPMediaPickerControllerDelegate>

@end
#import "ViewController.h"

@interface ViewController ()
@property(nonatomic, strong)MPMoviePlayerController *player;
@end

@implementation ViewController
- (IBAction)play:(id)sender {
    
    [self.view addSubview:self.player.view];
    self.player.shouldAutoplay = YES;
    self.player.fullscreen = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSBundle *b = [NSBundle mainBundle];
    NSString *path = [b pathForResource:@"test" ofType:@".mp4"];
    NSURL *url = [NSURL fileURLWithPath:path];
    self.player = [[MPMoviePlayerController alloc]initWithContentURL:url];
    
    // Do any additional setup after loading the view.
}

- (void)mediaPickerDidCancel:(MPMediaPickerController *)mediaPicker{
    [self.player.view removeFromSuperview];
}

@end

捕获视频缩略图

    // 向通知中心添加观察者,当请求缩略图发出时调用capture方法
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(capture:) name:MPMoviePlayerThumbnailImageRequestDidFinishNotification object:self.player];
    // 截屏时间点
    NSNumber *thirdSecondThumnail = [NSNumber numberWithFloat:3.0f];
    // 创建数组,此处只截一张图
    NSArray *requestedThumbnails = [NSArray arrayWithObject:thirdSecondThumnail];
    // 发出截屏请求
    [self.player requestThumbnailImagesAtTimes:requestedThumbnails timeOption:MPMovieTimeOptionExact];
-(void)capture:(NSNotification*)param{
    NSLog(@"capture...");
    UIImage *thumnail = [param.userInfo objectForKey:MPMoviePlayerThumbnailImageKey];
    self.imageView.image = thumnail;
}

选择系统音乐

in Build Phases -> Link Binary With Libraries, add "MediaPlayer.framework“ and “AVFoundation.framework”

#import "ViewController.h"

@interface ViewController ()
@property(nonatomic, strong)AVAudioPlayer *player;
@property(nonatomic, strong)NSURL *currentURL;
@end

@implementation ViewController
- (IBAction)play:(id)sender {
    
    if(self.player != nil){
        [self.player play];
    }
    
}
- (IBAction)stop:(id)sender {
    
    if(self.player != nil){
        [self.player stop];
    }
    
}
- (IBAction)select:(id)sender {
    
    MPMediaPickerController *picker = [[MPMediaPickerController alloc]initWithMediaTypes:MPMediaTypeAny];
    picker.delegate = self;
    picker.prompt = @"请选择...";
    picker.allowsPickingMultipleItems = YES;
    
    [self presentViewController:picker animated:YES completion:nil];
}
- (void)mediaPicker:(MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection{
    NSArray *items = mediaItemCollection.items;
    if(items.count > 0){
        MPMediaItem *item = [items objectAtIndex:0];
        self.currentURL = item.assetURL;
        self.player = [[AVAudioPlayer alloc]initWithContentsOfURL:self.currentURL error:nil];
    }
    [mediaPicker dismissViewControllerAnimated:YES completion:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Do any additional setup after loading the view.
}

@end

ERROR:原因是没有配置权限,iOS10以后需要配置权限才能访问

2019-04-19 11:01:55.174938+0800 04-06[4723:1980843] [MC] System group container for systemgroup.com.apple.configurationprofiles path is /private/var/containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles
2019-04-19 11:01:55.180228+0800 04-06[4723:1980843] [MC] Reading from public effective user settings.

solution:

在 Info.plist 中加入以下代码
<key>NSAppleMusicUsageDescription</key> 
<string>需要您的同意, APP才能访问媒体资料库</string>

在这里插入图片描述

拍照和录像

拍照

@property (strong, nonatomic) IBOutlet UIImageView *myImage;
@property (strong, nonatomic)UIImagePickerController *imgPicker;

- (IBAction)take:(id)sender {
    // 点击take 出现拍照界面
    [self presentViewController:self.imgPicker animated:YES completion:nil];
    
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<UIImagePickerControllerInfoKey, id> *)editingInfo{
    // 将照片展示在界面上
    self.myImage.image = image;
    // 返回主界面
    [self.imgPicker dismissViewControllerAnimated:YES completion:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.imgPicker = [[UIImagePickerController alloc]init];
    // 设置输入类型为照相机
    self.imgPicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    // 设置代理
    self.imgPicker.delegate = self;
    
    // Do any additional setup after loading the view.
}

录像

in Build Phases -> Link Binary With Libraries, add "MobileCoreServices.framework“.

#import "MobileCoreServices/MobileCoreServices.h"

- (IBAction)capture:(id)sender {
    
    [self presentViewController:self.imgPicker animated:YES completion:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.imgPicker = [[UIImagePickerController alloc]init];
    self.imgPicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    
    NSString *requireMediaType = (__bridge NSString*)kUTTypeMovie;
    self.imgPicker.mediaTypes = @[requireMediaType];
    // 设置代理
    self.imgPicker.delegate = self;
    // 是否允许编辑
    self.imgPicker.allowsEditing = YES;
    // 录制质量
    self.imgPicker.videoQuality = UIImagePickerControllerQualityTypeHigh;
    // 最大录制时间
    self.imgPicker.videoMaximumDuration = 30.0f;
    
    // Do any additional setup after loading the view.
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值