【发布时间】:2015-07-17 00:15:04
【问题描述】:
我正在开发一个音乐应用程序,它应该在后台播放音乐。
我使用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 中。
如何解决我的问题?我在互联网上没有找到任何东西。
在此先感谢您,费边。
【问题讨论】:
-
你的代码真的被执行了吗?
-
是的,[[MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo objectForKey:MPMediaItemPropertyTitle] 返回正确的 SongName。
-
啊哈!这真是个好消息。因此,您的代码不仅在运行,而且实际上成功设置了
nowPlayingInfo。所以让我问你这个 - 你是第一响应者,所以你成功地接收到来自锁屏和控制中心的远程控制事件? -
遥控器实际上并没有显示在锁定屏幕上,我不认为,我的应用程序成为第一响应者。
-
我认为这就是问题所在。除非您是第一响应者,否则您无法影响锁定屏幕。
标签: ios xcode mpmovieplayercontroller lockscreen audio-player