如何保存当前MPMediaItem的状态并在进入前台时响应更改的值

时间:2011-06-20 18:48:30

标签: iphone objective-c background nsuserdefaults mpmusicplayercontroller

所以我正在尝试开发一款使用iPod音乐库的音乐游戏。用户根据提示选择一首歌曲。因为我正在使用[MPMusicPlayerController iPodMusicPlayer],所以用户可能会在返回应用之前更改iPod应用中的歌曲。如果是这种情况,我希望它拨打[musicPlayer stop]。不幸的是,当应用程序从后台返回时,我无法弄清楚如何保存当前播放的歌曲并将其与当前播放的歌曲进行对比。请检查以下代码。

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    MPMusicPlayerController *musicPlayer = [MPMusicPlayerController iPodMusicPlayer];
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    NSString *persistantID = [musicPlayer.nowPlayingItem valueForProperty:MPMediaItemPropertyPersistentID];
    [prefs setValue:persistantID forKey:@"NOWPLAYING_ID"];

}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    MPMusicPlayerController *musicPlayer = [MPMusicPlayerController iPodMusicPlayer];
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    NSString *persistantID = [prefs stringForKey:@"NOWPLAYING_ID"];
    if (persistantID == [musicPlayer.nowPlayingItem valueForProperty:MPMediaItemPropertyPersistentID]) {
    }
    else {
        [musicPlayer stop];
    }
    [prefs setValue:nil forKey:@"NOWPLAYING_ID"];

}

任何人都可以帮我一把吗?非常感谢。

1 个答案:

答案 0 :(得分:1)

- (void)applicationWillResignActive:(UIApplication *)application    {
    self.mediaItemSavedWhenAppSuspended = [musicPlayer nowPlayingItem];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    MPMediaItem *nowPlayingItem = [musicPlayer nowPlayingItem];
    NSNumber *playingItem = [nowPlayingItem valueForProperty:MPMediaItemPropertyPersistentID];
    NSNumber *previousItem = [self.mediaItemSavedWhenAppSuspended valueForProperty:MPMediaItemPropertyPersistentID];

    if( [playingItem compare:previousItem] == NSOrderedSame )   {   //  same track still playing
   }