我正在开发一款音乐应用程序,它应该可以在后台播放音乐。
我使用 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];
时,音乐就开始播放了。
但我还想在锁屏界面和控制中心显示歌曲名称、专辑名称和专辑封面。我正在使用以下代码:
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];
}
但是在锁屏界面上没有显示任何内容。控制中心也没有显示出来。
我该怎么解决这个问题?我在网上没有找到任何有用的信息。
谢谢,Fabian。