1. 程式人生 > >iOS音樂後臺播放及鎖屏信息顯示

iOS音樂後臺播放及鎖屏信息顯示

found 能夠 elf mp3 tps info print pla remote


實現音樂的後臺播放。以及播放時,能夠控制其暫停,下一首等操作,以及鎖屏圖片歌曲名等的顯示
此實例須要真機調試。效果圖例如以下:
技術分享


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音樂後臺播放及鎖屏信息顯示