1.申请后台权限。Capabilities->Background Modes

2.设置后台播放模式

3.创建播放器
注意:AVAudioPlayer只能播放本地文件,且一次只能播放一个文件,如果需要上一曲、下一曲功能,可以通过创建多个AVAudioPlayer实现。

4.申请后台task
默认情况下切换到后台后,播放完当前音频后,就无法继续播放了。需要申请后台task;
在- (void)applicationWillResignActive:(UIApplication*)application中申请,在- (void)applicationWillEnterForeground:(UIApplication*)application取消。



5.后台控制
//开启后台处理多媒体事件
[[UIApplication sharedApplication]beginReceivingRemoteControlEvents];
在AppDelegare中处理

在相关类中处理:

6.显示歌曲信息
头文件:#import <MediaPlayer/MediaPlayer.h>
NSMutableDictionary *dict =[[NSMutableDictionary alloc]init];
//设置歌曲题目
[dict setObject:@"题目" forKey:MPMediaItemPropertyTitle];//设置歌手名
[dict setObject:@"歌手" forKey:MPMediaItemPropertyArtist];//设置专辑名
[dict setObject:@"专辑" forKey:MPMediaItemPropertyAlbumTitle];//设置显示的图片
UIImage *newImage = image;[dict setObject:[[MPMediaItemArtwork alloc]initWithImage:newImage] forKey:MPMediaItemPropertyArtwork];
//设置歌曲时长
[dict setObject:[NSNumber numberWithDouble:300]forKey:MPMediaItemPropertyPlaybackDuration];//设置已经播放时长
[dict setObject:[NSNumber numberWithDouble:150]forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime];//更新字典
[[MPNowPlayingInfoCenter defaultCenter]setNowPlayingInfo:dict];
网友评论