2015-05-11 5 views
1

После завершения каждой песни я очищаю очередь и добавляю новую очередь. Однако уведомление (воспроизведение/приостановка/остановка/воспроизведение/приостановка/воспроизведение/приостановка/приостановка) вызывается несколько раз. В конечном итоге он останавливает звук в приложении и начинает воспроизведение из iTunes.Как очистить очередь MPMusicPlayerController и добавить новую очередь, когда песня закончила в соответствии с требованием

Может ли кто-нибудь помочь мне с этим?

-(void)clearqueueAndAddNewQueue 
{ 
    NSMutableArray *allTheSongs = [[NSMutableArray alloc] initWithCapacity:0]; 

    NSLog(@"setupMusic:"); 
    for (SongsList *obj_songsList in arrSongs) { 

     // NSLog(@"mediaTitle: %@",obj_songsList.mediaTitle); 
     MPMediaQuery *songQuery = [MPMediaQuery songsQuery]; 
     [songQuery addFilterPredicate:[MPMediaPropertyPredicate predicateWithValue:obj_songsList.persistentId forProperty:MPMediaItemPropertyPersistentID]]; 
     NSArray *songs = [songQuery items]; 
     [allTheSongs addObjectsFromArray: songs]; 
    } 

    //Rearrange Array in Random Objects 
    NSUInteger count = [allTheSongs count]; 
    for (NSUInteger i = 0; i < count; ++i) { 
     // Select a random element between i and end of array to swap with. 
     NSInteger nElements = count - i; 
     NSInteger n = (arc4random() % nElements) + i; 
     [allTheSongs exchangeObjectAtIndex:i withObjectAtIndex:n]; 
    } 

    //Modify Queue 
    if ([[AppDelegate appDel].musicPlayerCtrl playbackState] == MPMusicPlaybackStatePlaying) { 

     MPMusicPlayerController *musicplayercontroller = [MPMusicPlayerController iPodMusicPlayer]; 
     MPMediaItemCollection *currentQueue = [[MPMediaItemCollection alloc] initWithItems:allTheSongs]; 
     MPMediaItem *nowPlaying = [[currentQueue items] objectAtIndex:0]; 
     [musicplayercontroller setQueueWithItemCollection:currentQueue]; 
     [musicplayercontroller setNowPlayingItem:nowPlaying]; 
     [AppDelegate appDel].musicPlayerCtrl = musicplayercontroller; 
    } 

    //I have also used this instead of above mentioed Modify Queue 
    if ([[AppDelegate appDel].musicPlayerCtrl playbackState] == MPMusicPlaybackStatePlaying) { 
     MPMediaPropertyPredicate *predicate = 
     [MPMediaPropertyPredicate predicateWithValue: @"Non_Existant_Song_Name" 
             forProperty: MPMediaItemPropertyTitle]; 
     MPMediaQuery *q = [[MPMediaQuery alloc] init]; 
     [q addFilterPredicate: predicate]; 
     [[AppDelegate appDel].musicPlayerCtrl setQueueWithQuery:q]; 
     [AppDelegate appDel].musicPlayerCtrl.nowPlayingItem = nil; 
     [[AppDelegate appDel].musicPlayerCtrl stop]; 



     MPMediaItemCollection *currentQueue = [[MPMediaItemCollection alloc] initWithItems:allTheSongs]; 
     [[AppDelegate appDel].musicPlayerCtrl setQueueWithItemCollection:currentQueue]; 
     [[AppDelegate appDel].musicPlayerCtrl play]; 
    } 
} 

ответ

0

Использование этого метода поможет очистить очередь и создать или добавить новую очередь без каких-либо проблем.

- (void)setupMusic:(NSArray *)arrSongs forTaggedValue:(NSString *)taggedValue { 

    NSMutableArray *allTheSongs = [[NSMutableArray alloc] initWithCapacity:0]; 
    NSLog(@"setupMusic:"); 
    for (SongsList *obj_songsList in arrSongs) { 

     // NSLog(@"mediaTitle: %@",obj_songsList.mediaTitle); 
     MPMediaQuery *songQuery = [MPMediaQuery songsQuery]; 
     [songQuery addFilterPredicate:[MPMediaPropertyPredicate predicateWithValue:obj_songsList.persistentId forProperty:MPMediaItemPropertyPersistentID]]; 
     NSArray *songs = [songQuery items]; 
     [allTheSongs addObjectsFromArray: songs]; 
    } 

    //Modify Queue 
    if ([[AppDelegate appDel].musicPlayerCtrl playbackState] == MPMusicPlaybackStatePlaying) { 

     [self removeNotificationCenterForMusicPlayerController]; 
     MPMediaPropertyPredicate *predicate = 
     [MPMediaPropertyPredicate predicateWithValue: @"Non_Existant_Song_Name" 
     forProperty: MPMediaItemPropertyTitle]; 
     MPMediaQuery *q = [[MPMediaQuery alloc] init]; 
     [q addFilterPredicate: predicate]; 
     [[AppDelegate appDel].musicPlayerCtrl setQueueWithQuery:q]; 
     [AppDelegate appDel].musicPlayerCtrl.nowPlayingItem = nil; 
     [[AppDelegate appDel].musicPlayerCtrl stop]; 

     MPMediaItemCollection *currentQueue = [[MPMediaItemCollection alloc] initWithItems:allTheSongs]; 
     [[AppDelegate appDel].musicPlayerCtrl setQueueWithItemCollection:currentQueue]; 
     [[AppDelegate appDel].musicPlayerCtrl setRepeatMode:MPMusicRepeatModeAll]; 
     [[AppDelegate appDel].musicPlayerCtrl play]; 

     [self addNotificationCenterForMusicPlayerController]; 
     [[AppDelegate appDel].musicPlayerCtrl beginGeneratingPlaybackNotifications]; 
    } 
} 

А также использовать этот код, который является полезным для работы вашего [AppDelegate appDel] .musicPlayerCtrl (объект MPMusicPlayerContoller), и предотвращает пойти в Itunes.

#pragma mark - For Hadle the Active Bugs Of MPMusicPlayerController 
- (BOOL)isPlaybackStateBugActive { 
    MPMusicPlaybackState playbackState = [AppDelegate appDel].musicPlayerCtrl.playbackState; 
    if (playbackState == MPMusicPlaybackStatePlaying) { 
     AudioSessionInitialize (NULL, NULL, NULL, NULL); 
     UInt32 sessionCategory = kAudioSessionCategory_AmbientSound; 
     AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (sessionCategory), &sessionCategory); 
     AudioSessionSetActive (true); 

     UInt32 audioIsPlaying; 
     UInt32 size = sizeof(audioIsPlaying); 
     AudioSessionGetProperty(kAudioSessionProperty_OtherAudioIsPlaying, &size, &audioIsPlaying); 

     if (!audioIsPlaying){ 
      NSLog(@"PlaybackState bug is active"); 
      [[AppDelegate appDel].musicPlayerCtrl pause]; 
      [btnPlayOrPause setImage:[UIImage imageNamed:KPlayImage] forState:UIControlStateNormal]; 
      return YES; 
     } 
    } 

    return NO; 
} 

addNotificationCenterForMusicPlayerController Метод

#pragma mark - Default NotificationCenter For iPodLibrary/MusicPlayerController 
- (void)addNotificationCenterForMusicPlayerController { 

    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; 

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

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



    // [notificationCenter addObserver: self selector: @selector (handle_VolumeChanged:) name: MPMusicPlayerControllerVolumeDidChangeNotification object: [AppDelegate appDel].musicPlayerCtrl]; 

    // [[AppDelegate appDel].musicPlayerCtrl beginGeneratingPlaybackNotifications]; 
} 

removeNotificationCenterForMusicPlayerController Метод

- (void)removeNotificationCenterForMusicPlayerController { 
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMusicPlayerControllerNowPlayingItemDidChangeNotification object: [AppDelegate appDel].musicPlayerCtrl]; 

    [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMusicPlayerControllerPlaybackStateDidChangeNotification object: [AppDelegate appDel].musicPlayerCtrl]; 

    // [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMusicPlayerControllerVolumeDidChangeNotification object: [AppDelegate appDel].musicPlayerCtrl]; 

    [[AppDelegate appDel].musicPlayerCtrl endGeneratingPlaybackNotifications]; 
}