我正在开发一个应该在后台播放音乐的音乐应用程序。
我用MPMoviePlayerController
播放音乐。我的代码启动MPMoviePlayerController
:
NSString* resourcePath = [[NSBundle mainBundle] resourcePath];
resourcePath = [resourcePath stringByAppendingString:@"/music.m4a"];
NSError* err;
self.player = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL fileURLWithPath:resourcePath]];
if (err) {
NSLog(@"ERROR: %@", err.localizedDescription);
}
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:nil];
[session setActive:YES error:nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self.player setShouldAutoplay:NO];
[self.player setControlStyle: MPMovieControlStyleEmbedded];
self.player.view.hidden = YES;
[self.player prepareToPlay];
当我执行[self.player play];
时,音乐开始了。但我还想在LockScreen和ControlCenter中显示歌曲名称,专辑名称和专辑插图。我正在使用以下代码:
Class playingInfoCenter = NSClassFromString(@"MPNowPlayingInfoCenter");
if (playingInfoCenter) {
NSMutableDictionary *songInfo = [[NSMutableDictionary alloc] init];
MPMediaItemArtwork *albumArt = [[MPMediaItemArtwork alloc] initWithImage: [UIImage imageNamed:@"artwork.png"]];
[songInfo setObject:@"SongName" forKey:MPMediaItemPropertyTitle];
[songInfo setObject:@"ArtistName" forKey:MPMediaItemPropertyArtist];
[songInfo setObject:@"AlbumTitle" forKey:MPMediaItemPropertyAlbumTitle];
[songInfo setObject:albumArt forKey:MPMediaItemPropertyArtwork];
[[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:songInfo];
}
但LockScreen中没有显示任何内容。它也不会显示在ControlCenter中。
我怎样才能解决我的问题?我没有在互联网上找到任何东西。
在此先感谢Fabian。
问题是你不能满足成为锁屏和控制中心的要求,如I explain in my book。您应该看到现代(iOS 8)相当于此:
您没有看到它的事实表明您省略了我列出的一个或多个要求(直接在我的书中引用):
canBecomeFirstResponder
返回YES,并且响应者实际上必须是第一响应者。remoteControlReceivedWithEvent:
。beginReceivingRemoteControlEvents
。我不知道你忽略了哪一个;它可能不止一个。您可能希望将代码与工作示例进行比较,此处:
想扩展@ matt的答案 - 当你使用AVAudioSessionCategoryOptionMixWithOthers
选项时,设置nowPlayingInfo是没用的。
进一步扩展@ matt的答案,当应用程序回到前台(endReceivingRemoteControlEvents
)时,需要调用resignFirstResponder
和applicationDidBecomeActive
。否则操作系统假设你是一个坏演员(或忘了关闭它们)并关闭你完全显示睡眠控制的能力,即使你再次打电话给beginReceivingRemoteControlEvents
。我添加了这些调用,现在睡眠控件总是显示它们应该的时间。
想解释@ zakhej的答案 - 设置AVAudioSessionCategoryOptionMixWithOthers时会发生什么。
所以。当您设置类别AVAudioSessionCategoryAmbient,AVAudioSessionCategoryPlayAndRecord并与其他人混合时,AVAudioSessionCategoryPlayback与其他人混合,设置MPNowPlayingInfoCenter的nowPlayingInfo是没用的。