MPMusicPlayerController不张贴通知?
我尝试使用MPMusicPlayerController
来播放音乐,我也想收到通知MPMusicPlayerControllerPlaybackStateDidChange
。我设置了我的播放器和通知注册几乎就像样品(工作,顺便说一句,它正确接收通知):
- (id) initWithPlaylist:(MPMediaPlaylist*)list { if (self = [super init]) { player = [MPMusicPlayerController applicationMusicPlayer]; [player retain]; NSLog(@"setting up player"); [plaayer setQueueWithItemCollection:list]; [player setShuffleMode:MPMusicShuffleModeOff]; [player setRepeatMode:MPMusicRepeatModeNone]; NSLog(@"registering MPMusicPlayerController Notifications"); [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handle_itemChanged:) name:MPMusicPlayerControllerNowPlayingItemDidChangeNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handle_stateChanged:) name:MPMusicPlayerControllerPlaybackStateDidChangeNotification object:nil]; NSLog(@"turning on player notifications"); [player beginGeneratingPlaybackNotifications]; } }
我得到了很多bupkis。 handle_itemChanged:
和handle_stateChanged:
方法只是空的,除了一个NSLog
语句显示它们已经被命中,并且它从来不会被命中。 initWithPlaylist:
中的NSLog
语句按预期打印到日志中。 以上只是我的应用程序中的一个业务对象。 这不是一个视图或视图控制器。
有任何想法吗? 奇怪的是AddMusic
示例对我来说工作得很好,我不能说我对MPMusicPlayerController
及其通知做了什么不同的事情。
更新 :我已经在我的应用程序委托中添加了这一行,以查看通知的完整泛滥:
[[NSNotificationCenter defaultCenter] addObserverForName:nil object:nil queue:nil usingBlock:^(NSNotification *n) { NSLog(@"notification: %@", n); }];
我看到各种通知被打印到控制台,但没有从媒体播放器控制器。
你应该在这些行上添加另一行:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handle_itemChanged:) name:MPMusicPlayerControllerNowPlayingItemDidChangeNotification object:nil];
那是:
[myPlayer beginGeneratingPlaybackNotifications];
它为我工作。
最后,我想出了答案:玩家必须在主线程中发送消息。 回想起来,这是有道理的,但直到现在才明白为止,它是完全不明显的。 我修改了我打开的错误是文档上的一个错误,因为我从来没有发现他们提到玩家必须在主线程中运行。