新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
iOS音樂后臺播放及鎖屏信息顯示
本文實例為大家分享了iOS實現(xiàn)音樂的后臺播放,以及播放時,可以控制其暫停,下一首等操作,以及鎖屏圖片歌曲名等的顯示
創(chuàng)新互聯(lián)公司是一家專注于網(wǎng)站建設(shè)、成都網(wǎng)站建設(shè)和內(nèi)江機房主機托管的網(wǎng)絡(luò)公司,有著豐富的建站經(jīng)驗和案例。
此實例需要真機調(diào)試,效果圖如下:
工程下載:github工程下載
實現(xiàn)步驟:
1、首先修改info.plist
2、其次引入兩個需要的框架
#import#import
3、設(shè)置播放器及后臺播放
- (void)viewDidLoad { [super viewDidLoad]; // 設(shè)置后臺播放 [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil]; // 設(shè)置播放器 NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"那些花兒" ofType:@"mp3"] ]; _player = [[AVPlayer alloc] initWithURL:url]; [_player play]; _isPlayingNow = YES; //后臺播放顯示信息設(shè)置 [self setPlayingInfo]; } #pragma mark - 接收方法的設(shè)置 - (void)remoteControlReceivedWithEvent:(UIEvent *)event { if (event.type == UIEventTypeRemoteControl) { //判斷是否為遠(yuǎn)程控制 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、設(shè)置后臺播放時顯示的東西,例如歌曲名字,圖片等
- (void)setPlayingInfo { //MPMediaItemArtwork *artWork = [[MPMediaItemArtwork alloc] initWithImage:[UIImage imageNamed:@"pushu.jpg"]]; NSDictionary *dic = @{MPMediaItemPropertyTitle:@"那些花兒", MPMediaItemPropertyArtist:@"樸樹", MPMediaItemPropertyArtwork:artWork }; [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:dic]; }
5、遠(yuǎn)程控制設(shè)置
- (void)viewDidAppear:(BOOL)animated { // 接受遠(yuǎn)程控制 [self becomeFirstResponder]; [[UIApplication sharedApplication] beginReceivingRemoteControlEvents]; } - (void)viewDidDisappear:(BOOL)animated { // 取消遠(yuǎn)程控制 [self resignFirstResponder]; [[UIApplication sharedApplication] endReceivingRemoteControlEvents]; }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。
名稱欄目:iOS音樂后臺播放及鎖屏信息顯示
標(biāo)題來源:http://fisionsoft.com.cn/article/jeijes.html