MPMediaItem不使用MPMediaItemPropertyAssetURL在AVAudioPlayer中播放

时间:2013-06-05 15:03:50

标签: ios objective-c avfoundation avaudioplayer

我有这个代码,找到并播放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);

我的日志:

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

但音频不播放。我有音量打开,另一个执行不同功能的AVAudioPlayer稍后播放音频。

1 个答案:

答案 0 :(得分:1)

AVAudioPlayer必须声明为属性或ivar,以便在方法完成后存活。