我正在尝试使用以下代码读取本地存储的音频文件的持续时间:
#import <Foundation/Foundation.h>
#import <CoreMedia/CoreMedia.h>
#import <AVFoundation/AVFoundation.h>
AVPlayer *player = [AVPlayer playerWithURL: urlForLocalAudioFile];
// busy wait - I know, not elegant, please ignore
int timeout = 0;
while (([player status] == AVPlayerStatusUnknown
|| [[player currentItem] status] == AVPlayerItemStatusUnknown)
&& timeout < 100) {
[NSThread sleepForTimeInterval: 0.1];
timeout++;
}
// make sure we have the right status
if ([[player currentItem] status] == AVPlayerItemStatusReadyToPlay) {
CMTime cmTime = [[player currentItem] duration];
if (CMTIME_IS_INDEFINITE(cmTime)) {
NSLog(@"Duration is kCMTimeIndefinite");
} else {
NSLog(@"Time: %d", CMTimeGetSeconds(cmTime));
}
} else {
NSLog(@"Item not ready to play");
}
该代码未在AppKit主线程中执行,并且曾经在macOS 10.13.x及更早版本下运行。现在,在10.14.0中,它始终报告
"Duration is kCMTimeIndefinite"
。即使在我开始播放文件之后。有人可以请:
谢谢。
最佳答案
是虫子吗?
是。参见rdar://45039043。
解决方法
使用
CMTime cmTime = [[[player currentItem] asset] duration];
代替CMTime cmTime = [[player currentItem] duration];