【发布时间】:2014-06-16 22:37:23
【问题描述】:
我在本地 iOS 音乐应用程序中获取当前正在播放的歌曲信息(如(标题、艺术家...)时遇到了一些问题。
这是确切的问题,我的应用程序使用 MPMusicPlayerController 和 iPodMusicPlayer 此属性调用 myPlayer。当用户在我的应用中控制音乐时,我可以通过这种方式显示当前的歌曲播放信息...
- (void)getTrackDescription {
// getting whats currently playing
self.nowPlayingItem = [myPlayer nowPlayingItem];
// song title currently playing
self.title = [self.nowPlayingItem valueForProperty:MPMediaItemPropertyTitle];
// if title is not fund Unknown will be displayed
if (title == (id)[NSNull null] || title.length == 0) {
title = @"Unknown";
}
// artist currently playing
self.artist = [self.nowPlayingItem valueForProperty:MPMediaItemPropertyArtist];
// if artist is not fund Unknown will be displayed
if (artist == (id)[NSNull null] || artist.length == 0) {
artist = @"Unknown";
}
//[self.currentlyPlaying setLineBreakMode:NSLineBreakByWordWrapping];
// displaying current artist and title song playing
[self.currentlyPlaying setText:[NSString stringWithFormat:@"%@ - %@", artist, title]];
}
但是,当用户将应用程序留在后台或仅使用 控制中心 更改歌曲时,问题就出现了。我的应用程序仍然显示以前的歌曲信息,如果用户继续使用控制中心或音乐应用程序本身。
我试着用这种方式解决问题……
- (void)viewDidLoad {
[super viewDidLoad];
if (self.myPlayer.playbackState == MPMusicPlaybackStatePlaying || self.myPlayer.playbackState == MPMusicPlaybackStateSeekingForward || self.myPlayer.playbackState == MPMusicPlaybackStateSeekingBackward){
// updating track name regardless the user uses app controllers or not
[self getTrackDescription];
}
}
我什至尝试评论 if 条件以查看我是否以这种方式获取歌曲信息,但这是同样的问题。
好吧,我希望有人可以帮助我并解释我做错了什么..
提前谢谢...!
更新
这是我目前拥有的...我的 getTrackDescription 逻辑是相同的,但签名更改为 - (void)getTrackDescription:(id)notification
- (void)viewWillAppear:(BOOL)animated{
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter addObserver:self
selector:@selector(getTrackDescription:)
name:MPMusicPlayerControllerPlaybackStateDidChangeNotification
object:self.myPlayer];
[self.myPlayer beginGeneratingPlaybackNotifications];
}
-(void)viewWillDisappear:(BOOL)animated{
[[NSNotificationCenter defaultCenter] removeObserver:self
name:MPMusicPlayerControllerPlaybackStateDidChangeNotification
object:self.myPlayer];
[self.myPlayer endGeneratingPlaybackNotifications];
}
【问题讨论】:
标签: ios objective-c ios7