AVAudioPlayer.duration 会在播放之后会有变化
https://stackoverflow.com/questions/16264282/avaudioplayer-duration-changing/16265186#16265186
self.player = [[AVAudioPlayer alloc] initWithData:[NSData dataWithContentsOfFile:self.outFilePath] error:nil];
NSTimeInterval duration = _player.duration;
AVURLAsset.duration 如何 option 不传也是有问题的
AVURLAsset*audioAsset = [AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:self.outFilePath] options:nil];
CMTime audioDuration = audioAsset.duration;
Float64 seconds = CMTimeGetSeconds(audioDuration)
需要设置下 AVURLAssetPreferPreciseDurationAndTimingKey 这个key
- (void)obtainDurationWithURLString:(NSString *)URLString identifier:(NSString *)identifier finished:(void (^)(NSTimeInterval duration))finished {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSURL * soundUrl = nil;
if ([URLString hasPrefix:@"http"] || [URLString hasPrefix:@"https"]) {
soundUrl = [NSURL URLWithString:URLString];
}else{
soundUrl = [NSURL fileURLWithPath:URLString];
}
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL: soundUrl options:[NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithBool:YES], AVURLAssetPreferPreciseDurationAndTimingKey, nil]];
float seconds = CMTimeGetSeconds(asset.duration);
dispatch_async(dispatch_get_main_queue(), ^{
if (finished) {
finished(seconds);
}
});
});
}
参考:
https://stackoverflow.com/questions/23606998/avaudioplayer-returns-wrong-file-duration
https://cloud.tencent.com/developer/ask/128150