MPMediaItem not playing in AVAudioPlayer using MPMediaItemPropertyAssetURL

随声附和 提交于 2019-12-22 08:16:42

问题


I have this code, to find and play a 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 log:

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

But the audio doesn't play. I have volume on, and another AVAudioPlayer, performing a different function, plays its audio fine later on.


回答1:


The AVAudioPlayer must be declared as a property or ivar so it survives after the method is finalized.



来源:https://stackoverflow.com/questions/16943336/mpmediaitem-not-playing-in-avaudioplayer-using-mpmediaitempropertyasseturl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!