I"m trying to use the MPMusicPlayerController
to play music, and I also want to receive the notification MPMusicPlayerControllerPlaybackStateDidChange
. I set up my player and notification registration pretty much just like the sample (which works, BTW - it receives notifications correctly):
- (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];
}
}
I get a whole lot of bupkis. The methods handle_itemChanged:
and handle_stateChanged:
are just empty except for an NSLog
statement to show they've been hit, and it never appears that they get hit. The NSLog
statements in initWithPlaylist:
are printed to the log as expected. The above is just a business object in my app. It's not a view or view controller.
Any ideas? The bizarre thing is that the AddMusic
sample works just fine for me, and I can't tell that I"m doing anything differently with regard to the MPMusicPlayerController
and its notifications.
Update: I've added this line in my app delegate to see the full flood of notifications:
[[NSNotificationCenter defaultCenter] addObserverForName:nil object:nil queue:nil usingBlock:^(NSNotification *n) { NSLog(@"notification: %@", n); }];
I see all kinds of notifications being printed to the console, but none from the media player controller.
You should add another line above these lines:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(handle_itemChanged:)
name:MPMusicPlayerControllerNowPlayingItemDidChangeNotification
object:nil];
that is:
[myPlayer beginGeneratingPlaybackNotifications];
it worked for me.
Finally, I figured out the answer: the player has to be sent messages on the main thread. It makes some sense in retrospect, but it was completely non-obvious until the moment it dawned on me. I modified the bug I opened to be a bug on the documentation because I never did spot where they mentioned that the player must be operated on the main thread.
精彩评论