简体   繁体   中英

AVPlayer + MPNowPlayingInfoCenter works on simulator but not on device

I am using AVPlayer to reproduce music. All is working just fine on simulator with iOS 6+. But when I run it on device (iPhone 5s, iOS 7.1), MPNowPlayingInfoCenter shows info from any other music apps: spotify / sound cloud / music player, instead of current playing item in my application.

Here is the code I use to set music info in MPNowPlayingInfoCenter:

- (void)setupNowPlayingInfoCenter
{
    if (NSClassFromString(@"MPNowPlayingInfoCenter")) {
        // Here enters fine.
        MPNowPlayingInfoCenter *playingInfoCenter = [MPNowPlayingInfoCenter defaultCenter];

        if (self.playingUrl) {
            NSMutableDictionary *songInfo = self.songInfo;

            MPMediaItemArtwork *albumArt = [[MPMediaItemArtwork alloc] initWithImage:[self.playingObject valueForKey:@"image"]];

            [songInfo setObject:[self.playingObject valueForKey:@"song"] forKey:MPMediaItemPropertyTitle];
            [songInfo setObject:[self.playingObject valueForKey:@"artist"] forKey:MPMediaItemPropertyArtist];
            [songInfo setObject:[self.playingObject valueForKey:@"album"] forKey:MPMediaItemPropertyAlbumTitle];
            [songInfo setObject:[NSNumber numberWithDouble:self.progress] forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime];
            [songInfo setObject:[NSNumber numberWithDouble:self.duration] forKey:MPMediaItemPropertyPlaybackDuration];
            [songInfo setObject:(self.isPaused ? @(0.0f) : @(1.0f)) forKey:MPNowPlayingInfoPropertyPlaybackRate];
            [songInfo setObject:albumArt forKey:MPMediaItemPropertyArtwork];

            playingInfoCenter.nowPlayingInfo = songInfo;
}

Other related code:

- (NSError *)initialize
{
    NSError *error = nil;
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryPlayback 
                        error:&error];
    if (error) {
        NSLog(@"%@", [error description]);
        return error;
    }
    [audioSession setActive:YES error:&error];
    if (error) {
        NSLog(@"%@", [_error description]);
        return error;
    }

    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    return error;
}

Any help will be much appreciated.

All right, I found the answer myself.

I was creating new player each song, like this:

self.audioPlayer = [AVPlayer playerWithURL:url];

I changed it with:

AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:url];
[self.audioPlayer replaceCurrentItemWithPlayerItem:playerItem];

and magically it started to work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM