MPMediaItem does not play in AVAudioPlayer using MPMediaItemPropertyAssetURL

I have this code to find and play MPMediaItem:

MPMediaPropertyPredicate *predicate = [MPMediaPropertyPredicate predicateWithValue:self.persistentIDOfSongToPlay forProperty:MPMediaItemPropertyPersistentID comparisonType:MPMediaPredicateComparisonContains]; NSSet *predicateSet = [NSSet setWithObject:predicate]; MPMediaQuery *searchQuery = [[MPMediaQuery alloc] initWithFilterPredicates:predicateSet]; NSArray *queryResults = [searchQuery items]; NSLog(@"count: %i", queryResults.count); MPMediaItem *item = [queryResults objectAtIndex:0]; NSLog(@"item: %@", item); NSURL *itemURL = [item valueForProperty:MPMediaItemPropertyAssetURL]; NSLog(@"url: %@", itemURL); NSError *error; AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:itemURL error:&error]; [audioPlayer prepareToPlay]; [audioPlayer play]; NSLog(@"error: %@", error); 

My journal:

 count: 1 item: <MPConcreteMediaItem: 0x200b0870> 12385304089059716916 url: ipod-library://item/item.m4a?id=-6061439984649834700 error: (null) 

But the sound does not play. I have a volume, and another AVAudioPlayer, which performs another function, later plays the sound.

+4
source share
1 answer

AVAudioPlayer must be declared as a property or ivar so that it survives after the method completes.

0
source

Source: https://habr.com/ru/post/1484666/


All Articles