码迷,mamicode.com
首页 > 移动开发 > 详细

iOS音乐后台播放及锁屏信息显示

时间:2017-07-30 15:54:15      阅读:273      评论:0      收藏:0      [点我收藏+]

标签:project   processor   role   init   lis   取消   isa   oid   sap   


实现音乐的后台播放。以及播放时,能够控制其暂停,下一首等操作,以及锁屏图片歌曲名等的显示
此实例须要真机调试。效果图例如以下:
技术分享


project下载:githubproject下载


实现步骤:
1、首先改动info.plist
技术分享


2、其次引入两个须要的框架

#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>

3、设置播放器及后台播放

- (void)viewDidLoad {
    [super viewDidLoad];
//    设置后台播放
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];

//    设置播放器
    NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"那些花儿" ofType:@"mp3"] ];
    _player = [[AVPlayer alloc] initWithURL:url];
    [_player play];
    _isPlayingNow = YES;

    //后台播放显示信息设置
    [self setPlayingInfo];
}

#pragma mark - 接收方法的设置
- (void)remoteControlReceivedWithEvent:(UIEvent *)event {
    if (event.type == UIEventTypeRemoteControl) {  //推断是否为远程控制
        switch (event.subtype) {
            case  UIEventSubtypeRemoteControlPlay:
                if (!_isPlayingNow) {
                    [_player play];
                }
                _isPlayingNow = !_isPlayingNow;
                break;
            case UIEventSubtypeRemoteControlPause:
                if (_isPlayingNow) {
                    [_player pause];
                }
                _isPlayingNow = !_isPlayingNow;
                break;
            case UIEventSubtypeRemoteControlNextTrack:
                NSLog(@"下一首");
                break;
            case UIEventSubtypeRemoteControlPreviousTrack:
                NSLog(@"上一首 ");
                break;
            default:
                break;
        }
    }
}

4、设置后台播放时显示的东西,比如歌曲名字。图片等

- (void)setPlayingInfo {
//    <MediaPlayer/MediaPlayer.h>
    MPMediaItemArtwork *artWork = [[MPMediaItemArtwork alloc] initWithImage:[UIImage imageNamed:@"pushu.jpg"]];

    NSDictionary *dic = @{MPMediaItemPropertyTitle:@"那些花儿",
                          MPMediaItemPropertyArtist:@"朴树",
                          MPMediaItemPropertyArtwork:artWork
                          };
    [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:dic];
}

5、远程控制设置

- (void)viewDidAppear:(BOOL)animated {
//    接受远程控制
    [self becomeFirstResponder];
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
}

- (void)viewDidDisappear:(BOOL)animated {
//    取消远程控制
    [self resignFirstResponder];
    [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
}

iOS音乐后台播放及锁屏信息显示

标签:project   processor   role   init   lis   取消   isa   oid   sap   

原文地址:http://www.cnblogs.com/clnchanpin/p/7259137.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!