Realize the background play of music, as well as play, can control its pause, the next operation, as well as the lock screen picture song name and so on display
This instance requires real-machine debugging, as follows:
Project download: GitHub project Download
Implementation steps:
1, first modify Info.plist
2, followed by the introduction of two required framework
#import <AVFoundation/AVFoundation.h>#import <MediaPlayer/MediaPlayer.h>
3. Set player and background play
- (void) Viewdidload {[SuperViewdidload];//Set background playback[[avaudiosession sharedinstance] Setcategory:avaudiosessioncategoryplayback error:Nil];//Set player Nsurl*url = [Nsurlfileurlwithpath:[[NSBundleMainbundle] pathforresource:@"those flowers."oftype:@"MP3"] ]; _player = [[Avplayer alloc] initwithurl:url]; [_player play]; _isplayingnow =YES;//Background playback display information Settings[ SelfSetplayinginfo];}#pragma mark-the settings of the Receive method- (void) Remotecontrolreceivedwithevent: (Uievent *) Event {if(Event. Type= = Uieventtyperemotecontrol) {//Determine if remote control is Switch(Event. Subtype) { CaseUieventsubtyperemotecontrolplay:if(!_isplayingnow) {[_player play]; } _isplayingnow =!_isplayingnow; Break; CaseUieventsubtyperemotecontrolpause:if(_isplayingnow) {[_player pause]; } _isplayingnow =!_isplayingnow; Break; CaseUieventsubtyperemotecontrolnexttrack:NSLog(@"Next Song"); Break; CaseUieventsubtyperemotecontrolprevioustrack:NSLog(@"The Last Song"); Break;default: Break; } }}
4, set the background to display things, such as song name, pictures, etc.
- (void)setPlayingInfo {// <MediaPlayer/MediaPlayer.h> [[MPMediaItemArtwork alloc] initWithImage:[UIImage imageNamed:@"pushu.jpg"]]; NSDictionary *dic = @{MPMediaItemPropertyTitle:@"那些花儿", MPMediaItemPropertyArtist:@"朴树", MPMediaItemPropertyArtwork:artWork }; [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:dic];}
5. Remote Control Settings
- (void)viewDidAppear:(BOOL)animated {// 接受远程控制 [self becomeFirstResponder]; [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];}- (void)viewDidDisappear:(BOOL)animated {// 取消远程控制 [self resignFirstResponder]; [[UIApplication sharedApplication] endReceivingRemoteControlEvents];}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
iOS music background playback and lock screen information display