我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;
}];
}];
}
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,currentItemIsvoid被调用,但是当轨道完成播放时它会运行.我希望在轨道开始时调用它.
编辑: 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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
首先,您需要注册您AVPlayerItem的观察员:
[self.yourPlayerItem addObserver:self
forKeyPath:kStatus
options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew
context:AVPlayerStatus];
Run Code Online (Sandbox Code Playgroud)
然后在您的播放器Key Value Observer方法中,您需要检查AVPlayerStatusReadyToPlay 状态,如下所示:
- (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.
}
break;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8348 次 |
| 最近记录: |