我遇到了关于
我想知道的是,当一个音乐文件刚开始播放时,而不是它播放结束时(通过
我的代码:
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 被调用,但它是在曲目播放完成后运行的。我希望它在曲目开始时被调用。
编辑: Winston 代码片段的更新版本:
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;
}
}
}
playerItem
上,并且将AVPlayerStatus
定义为上下文并检查AVPlayerStatus
。而你应该检查#keyPath(AVPlayer.currentItem.status)
或AVPlayerItem.Status
而不是AVPlayerStatus
,因为你的观察者是为项目而不是播放器添加的。 - Coder ACJHP