我遇到了AVPlayerItem
和的问题AVQueuePlayer
。目前我有很多 1-2 秒长的音乐文件和一个用于按顺序播放它们的队列播放器。
我想知道音乐文件何时开始播放,而不是何时完成播放(通过AVPlayerItemDidPlayToEndTimeNotification
)。
这是因为我想在加载和播放新文件时运行一个函数。
我的代码:
for (NSUInteger i = 0; i < [matchedAddr count]; i++)
{
NSString *firstVideoPath = [[NSBundle mainBundle] pathForResource:[matchedAddr objectAtIndex:i] ofType:@"wav"];
//NSLog(@"file %@",firstVideoPath);
avitem=[AVPlayerItem playerItemWithURL:[NSURL fileURLWithPath:firstVideoPath]];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(currentItemIs:)
name:AVPlayerItemDidPlayToEndTimeNotification
object:avitem];
[filelist addObject:avitem];
}
player = [AVQueuePlayer queuePlayerWithItems:filelist];
[player play];
- (void)currentItemIs:(NSNotification *)notification
{
NSString *asd=[seqArray objectAtIndex:currentColor];
currentColor=currentColor+1;
AVPlayerItem *p = [notification object];
[p seekToTime:kCMTimeZero];
if([asd isEqual:@"1"])
{
[UIView animateWithDuration:0.01 animations:^{
one.alpha = 0;
} completion:^(BOOL finished) {
[UIView animateWithDuration:0.01 animations:^{
one.alpha = 1;
}];
}];
}
}
如您所见,currentItemIs
void 被调用,但它在曲目播放完毕时运行。我想在曲目开始时被调用。
编辑: 温斯顿片段的更新版本:
NSString * const kStatusKey = @"status";
[avitem addObserver:self
forKeyPath:kStatusKey
options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew
context:@"AVPlayerStatus"];
- (void)observeValueForKeyPath:(NSString *)path
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context {
if (context == @"AVPlayerStatus") {
AVPlayerStatus status = [[change objectForKey:NSKeyValueChangeNewKey] integerValue];
switch (status) {
case AVPlayerStatusUnknown: {
}
break;
case AVPlayerStatusReadyToPlay: {
// audio will begin to play now.
NSLog(@"PLAU");
[self playa];
}
break;
}
}
}