iOS多媒体总结&进入后台播放音乐

1. 播放mp3需要导入框架,AVFoundation支持音频文件(.caf、.aif、.wav、.wmv和.mp3)的播放。

#import <AVFoundation/AVFoundation.h>//音频播放框架

步骤:

a.声明一个音频播放对象:

{
   AVAudioPlayer *_player;
}

b.用一个支持的文件路径来初始化_player: (据说只能播放本地文件,像酷我等音乐软件应该是播放前下载到本地,然后进行播放的,因为在用酷我时,隔断时间就会提示我内存过大,请清理,应该就清理下载到到本地的音频文件)

    NSString *path=[[NSBundle mainBundle]pathForResource:@"纯音乐-The True That You Leave" ofType:@"mp3"];
    _player=[[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:path] error:nil];
    [_player prepareToPlay];
    [_player play];
    //[_player pause];暂停
    //[_player stop];停止
    _player.volume=1;//音量 0.0-1.0

c. 如果想看播放时间可以注册一个定时器:

[NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(player) userInfo:nil repeats:YES];
NSLog(@"音频当前时间%lf",_player.currentTime);//音频当前时间
NSLog(@"音频总时间%lf",_player.duration);//音频总时间

d. 这样就实现了,如果想加个进度条,可以用UISlider: 下面这个是从Xib中拖出来的

@property (weak, nonatomic) IBOutlet UISlider *musicPlaySlider;

//更新时间进度条这样做
    self.musicPlaySlider.value = (float)_player.currentTime/_player.duration;

//想移动UISlider 从指定那个时刻开始播放这样做
    [self.musicPlaySlider addTarget:self action:@selector(moveMusicPlaySlider:) forControlEvents:UIControlEventValueChanged];

然后实现moveMusicPlaySlider:方法:
-(void)moveMusicPlaySlider:(UISlider *)sender{
    NSLog(@"slider改变%f",sender.value);
    self.musicPlaySlider.value = sender.value;
    [_player stop];
    _player.currentTime = _player.duration * sender.value;//给指定位置播放
    [_player play];
    
}

音乐进度条3方应该很好找吧...

 

2. 播放mp4需要导入

#import <MediaPlayer/MediaPlayer.h>

步骤:

a. 声明一个视频播放器控制器

@property (nonatomic,strong) MPMoviePlayerController *moviePlayer;

b. 初始化moviePlayer可以放到懒加载:

-(MPMoviePlayerController *)moviePlayer {
  
    if (!_moviePlayer) {
        NSURL *url = [self getFileUrl];
        _moviePlayer = [[MPMoviePlayerController alloc]initWithContentURL:url];
        _moviePlayer.view.frame = self.view.bounds;
        _moviePlayer.view.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
        [self.view addSubview:_moviePlayer.view];
    }
    return _moviePlayer;
}

c. 开始播放:

//播放
    [self.moviePlayer play];
如果想看播放状态,截屏等 可以写一个方法注册通知:
-(void)addNotification {

    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
    [notificationCenter addObserver:self selector:@selector(mediaPlayerPlaybackStateChange:) name:MPMoviePlayerPlaybackStateDidChangeNotification object:self.moviePlayer];
    [notificationCenter addObserver:self selector:@selector(mediaPlayerPlaybackFinished:) name:MPMoviePlayerPlaybackDidFinishNotification object:self.moviePlayer];
    //缩略图截屏完成
    [notificationCenter addObserver:self selector:@selector(mediaPlayerThumbnailRequestFinished:) name:MPMoviePlayerThumbnailImageRequestDidFinishNotification object:self.moviePlayer];
    
}

然后这个方法里查看播放状态:
-(void)mediaPlayerPlaybackStateChange:(NSNotification *)notification {
    /*
     MPMoviePlaybackStateStopped,
     MPMoviePlaybackStatePlaying,
     MPMoviePlaybackStatePaused,
     MPMoviePlaybackStateInterrupted,
     MPMoviePlaybackStateSeekingForward,
     MPMoviePlaybackStateSeekingBackward
     */
    switch (self.moviePlayer.playbackState) {
        case MPMoviePlaybackStatePlaying:
            NSLog(@"playing...");
            break;
        case MPMoviePlaybackStatePaused:
            NSLog(@"paused...");
            break;
        case MPMoviePlaybackStateStopped:
            NSLog(@"stop...");
            break;
        default:
            NSLog(@"playsatus...%li",self.moviePlayer.playbackState);
            break;
    }
}

如果想播放时指定时间点截图可以这样做:
//获取2.0s时刻缩略图
    [self.moviePlayer requestThumbnailImagesAtTimes:@[@2.0] timeOption:MPMovieTimeOptionNearestKeyFrame];
然后在上面通知里的方法处理截图:
// 缩略图请求完成,此方法每次截图成功都会调用一次
-(void)mediaPlayerThumbnailRequestFinished:(NSNotification *)notification{
    /*
     {name = MPMoviePlayerThumbnailImageRequestDidFinishNotification; object = <MPMoviePlayerController: 0x608000004ba0>; userInfo = {
     MPMoviePlayerThumbnailImageKey = "<UIImage: 0x6080000914e0>, {640, 352}";
     MPMoviePlayerThumbnailTimeKey = 0;
     }}
     */
    NSLog(@"视频截图完成...%@",notification);
    UIImage *image=notification.userInfo[MPMoviePlayerThumbnailImageKey];
    //保存图片到相册(首次调用会请求用户获得访问相册权限)
    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
    //保存截图会暂停播放,继续
    if (self.moviePlayer.playbackState == 2) {
        [self.moviePlayer play];
    }
}



 

3. 调用系统相册

UIImagePickerController *imagePicker=[[UIImagePickerController alloc]init];
    imagePicker.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
//    UIImagePickerControllerSourceTypePhotoLibrary,相册
//    UIImagePickerControllerSourceTypeCamera,调用相机
//    UIImagePickerControllerSourceTypeSavedPhotosAlbum相簿
    imagePicker.delegate=self;
    [self presentViewController:imagePicker animated:YES completion:^{}];

然后在代理方法中处理图片:
#pragma mark - UIImagePickerControllerDelegate
//照片选择完成回调代理
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{

}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo{
    UIImageView *view=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    [view setImage:image];
    [self.view addSubview:view];
}

 

基本使用就这些...待完善

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

看到黑马做的那个百度音乐播放器,自己照着视频写了一遍,也没有很好的完善,就是熟悉了一下大致思路 Demo地址:

https://github.com/nwgdegitHub/musicPlayDemo

 

4. 模拟器上进入后台仍能播放音乐,真机上要设置2个地方,一个是Capabilities中Backgroud Modes的第一个开关,另一个是在Appdelegate加点代码:

UIBackgroundTaskIdentifier _bgTaskId;
- (void)applicationWillResignActive:(UIApplication *)application {
    
    //开启后台处理多媒体事件
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    AVAudioSession *session=[AVAudioSession sharedInstance]; [session setActive:YES error:nil];
    //后台播放
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    //这样做,可以在按home键进入后台后 ,播放一段时间,几分钟吧。但是不能持续播放网络歌曲,若需要持续播放网络歌曲,还需要申请后台任务id,具体做法是:
    _bgTaskId = [AppDelegate backgroundPlayerID:_bgTaskId];
}
//实现一下backgroundPlayerID:这个方法:
+(UIBackgroundTaskIdentifier)backgroundPlayerID:(UIBackgroundTaskIdentifier)backTaskId {
    //设置并激活音频会话类别
    AVAudioSession *session=[AVAudioSession sharedInstance]; [session setCategory:AVAudioSessionCategoryPlayback error:nil]; [session setActive:YES error:nil];
    //允许应用程序接收远程控制
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    //设置后台任务ID
    UIBackgroundTaskIdentifier newTaskId=UIBackgroundTaskInvalid; newTaskId=[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil]; if(newTaskId!=UIBackgroundTaskInvalid&&backTaskId!=UIBackgroundTaskInvalid) { [[UIApplication sharedApplication] endBackgroundTask:backTaskId]; } return newTaskId;
}

这样就能实现进入后台播放了。参考来自  http://www.jianshu.com/p/03d80157948a

 

posted @ 2017-09-11 19:18  liuw_flexi  阅读(591)  评论(0编辑  收藏  举报