[英]How to Implementing MPNowPlayingInfoCenter using AvAudioPlayer
I am in the midst of creating an iOS mobile app for a client that will play a variety of audio tracks. 我正在为一个将播放各种音轨的客户端创建iOS移动应用程序。
One of the features that I wanted to implement was to display information about a currently-playing audio track on the lock screen and banner . 我要实现的功能之一是在锁屏和横幅上显示有关当前播放的音轨的信息。 This is one of those simple convenience to a mobile user and a must-have if your app has background audio playing.
这是给移动用户带来的简单便利之一,并且如果您的应用程序具有背景音频播放功能,则必须具备这些便利。 Personally, I use this feature all the time!
我个人一直在使用此功能!
You should first observe the AVPlayerItem
of AVAudioPlayer
like so: 您应该首先像这样观察
AVAudioPlayer
的AVPlayerItem
:
[playerItem addObserver:self forKeyPath:@"timedMetadata" options:NSKeyValueObservingOptionNew context:nil];
Then create some global variables: 然后创建一些全局变量:
NSString *title;
NSString *artist;
UIImage *artwork;
You would then probably need a function like the one below, so you observe the key path timedMetadata
and update the InfoCenter through updateInfoCenterWithTitle:andArtist:andCover:
. 然后,您可能需要一个类似于以下功能的函数,因此您观察关键路径
timedMetadata
并通过updateInfoCenterWithTitle:andArtist:andCover:
更新信息中心。
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([keyPath isEqualToString:@"timedMetadata"])
{
for (int i = 0; i < [audioPlayer.currentItem.timedMetadata count]; i++)
{
AVMetadataItem *metaData = [audioPlayer.currentItem.timedMetadata objectAtIndex:i];
if ([[metaData commonKey] isEqualToString:AVMetadataCommonKeyArtist]) {
artist = (NSString *)metaData.value;
}
else if ([[metaData commonKey] isEqualToString:AVMetadataCommonKeyTitle])
{
title = (NSString *)metaData.value;
[self updateInfoCenterWithTitle:title andArtist:artist andCover:artwork];
}
else if ([[metaData commonKey] isEqualToString:AVMetadataCommonKeyArtwork])
{
if ([metaData.keySpace isEqualToString:AVMetadataKeySpaceID3])
{
NSDictionary *dictionary = [metaData.value copyWithZone:nil];
artwork = [UIImage imageWithData:[dictionary objectForKey:@"data"]]];
} else if ([metaData.keySpace isEqualToString:AVMetadataKeySpaceiTunes]) {
artwork = [UIImage imageWithData:[metaData.value copyWithZone:nil]];
}
}
else {
NSLog(@"%@ --> %@", [metaData commonKey], metaData.value);
}
}
}
}
This is where the magic happens: 这就是魔术发生的地方:
- (void)updateInfoCenterWithTitle:(NSString *)title andArtist:(NSString *)artist andCover:(UIImage *)cover
{
if (cover == nil) {
cover = [UIImage imageNamed:@"defaultCover"];
}
MPNowPlayingInfoCenter *infoCenter = [MPNowPlayingInfoCenter defaultCenter];
[infoCenter setNowPlayingInfo:@{MPMediaItemPropertyTitle:title,
MPMediaItemPropertyArtist:artist,
MPMediaItemPropertyArtwork:[[MPMediaItemArtwork alloc] initWithImage:cover]}];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.