iOS:在某些设备上多次调用MPMusicPlayerControllerPlaybackStateDidChangeNotification

时间:2012-07-06 14:47:31

标签: ios ipad mpmediaplayercontroller

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

我使用以下代码从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)上运行 strong>我得到以下序列而不是只有一个回调:

-[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次,交替值。

有关如何解决这个问题的建议或建议我还可以测试什么来缩小问题范围?


由于到目前为止我还没有收到答案,我还将问题交叉发布到 Apple开发者论坛https://devforums.apple.com/thread/158426

2 个答案:

答案 0 :(得分:0)

我认为这与此处报道的错误相同:

Getting wrong playback state in MP Music Player Controller in ios 5

我发布了该问题中的错误的解决方法。

答案 1 :(得分:0)

您可以使用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;
    }
}

因此可以切断误暂停通知。