iOS版:MPMusicPlayerControllerPlaybackStateDidChange

2019-09-19 04:48发布

我有一个播放音乐的应用。

我使用下面的代码来听回放从MPMusicPlayerController状态变化来更新UI。 更确切地说我切换播放和暂停的播放按钮的外观。

NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];

[notificationCenter addObserver: self
                       selector: @selector (handle_NowPlayingItemChanged:)
                           name: MPMusicPlayerControllerNowPlayingItemDidChangeNotification
                         object: self.musicPlayer];

[notificationCenter addObserver: self
                       selector: @selector (handle_PlaybackStateChanged:)
                           name: MPMusicPlayerControllerPlaybackStateDidChangeNotification
                         object: self.musicPlayer];

[self.musicPlayer beginGeneratingPlaybackNotifications];

这对一部iPod touch(iOS 5中)iPhone 3GS(iOS 5中)的伟大工程。 每次回放状态的变化,我得到以下回调:

[JBMediaPlayer handle_PlaybackStateChanged:] :: playbackState: 1

其中1表示MPMusicPlaybackStatePlaying

然而,如果我运行一台iPad 1(的iOS 5)是相同的,iPad 2的(的iOS 5)ipad 3(的iOS 6)得到以下序列,而不只是一个单一的回调:

-[JBMediaPlayer handle_PlaybackStateChanged:] :: playbackState: 1
-[JBMediaPlayer handle_PlaybackStateChanged:] :: playbackState: 2
-[JBMediaPlayer handle_PlaybackStateChanged:] :: playbackState: 1
-[JBMediaPlayer handle_PlaybackStateChanged:] :: playbackState: 2

其中,2表示MPMusicPlaybackStatePaused并导致我的应用程序在UI中显示的错误状态,因为这首歌实际上是正在播放。

有趣的是,曾经在一段时间的序列

-[JBMediaPlayer handle_PlaybackStateChanged:] :: playbackState: 1
-[JBMediaPlayer handle_PlaybackStateChanged:] :: playbackState: 2
-[JBMediaPlayer handle_PlaybackStateChanged:] :: playbackState: 1
-[JBMediaPlayer handle_PlaybackStateChanged:] :: playbackState: 2
-[JBMediaPlayer handle_PlaybackStateChanged:] :: playbackState: 1

与1正确地结束了MPMusicPlaybackStatePlaying ,但是仍然没有任何意义的回调函数被调用5次,交替值。

如何解决这个或建议,还有什么我能考到缩小问题的任何想法?


因为在这里我没有收到答复,到目前为止,我还交张贴问题向苹果开发者论坛 : https://devforums.apple.com/thread/158426

Answer 1:

我认为这是此报告的同样的bug:

获取错误的播放状态MP音乐播放器在iOS 5中

我发布了解决办法在这个问题的错误。



Answer 2:

您可以使用currentPlaybackRate属性检查实际的播放状态。 MPMusicPlaybackStatePaused必须匹配率0.0。 它如何实现的例子如下所示:...

- (void)musicPlayerControllerPlaybackStateDidChangeNotification:(NSNotification *)notification {
    float playbackRate = [((MPMusicPlayerController *)notification.object) currentPlaybackRate];
    MPMusicPlaybackState playbackState = (MPMusicPlaybackState)[notification.userInfo[@"MPMusicPlayerControllerPlaybackStateKey"] integerValue];
    switch (playbackState) {
        case MPMusicPlaybackStatePaused:
            if (playbackRate <= .0f) {
                self.playbackState = playbackState;
            }
            break;
        default:
            self.playbackState = playbackState;
            break;
    }
}

因此,有可能切断虚假暂停通知。



文章来源: iOS: MPMusicPlayerControllerPlaybackStateDidChangeNotification called multiple times on certain devices