Enable background playback of music. And when playing, 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. For example, the following:
Project Download: Githubproject download
Implementation steps:
1, first change 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) {//Infer whether it is a remote control 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];}
iOS music background playback and lock screen information display