【已解决】OS X下AVPlayer无法立即获取duration

源代码如下:

#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface ViewController ()

@property AVPlayer *player;
@property Float64 duration;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // Do any additional setup after loading the view.
}
- (IBAction)btn_player:(id)sender {
    NSURL* url = [NSURL fileURLWithPath:@"/Users/ben_gao/Desktop/1.mp3"];
    if(!_player){
        NSLog(@"initialize...");
        _player = [[AVPlayer alloc] initWithURL:url];
    }
    _duration = CMTimeGetSeconds(_player.currentItem.duration);
    NSLog(@"%f",_duration);
}


- (void)setRepresentedObject:(id)representedObject {
    [super setRepresentedObject:representedObject];

    // Update the view, if already loaded.
}


@end

 解决方案:

    AVURLAsset *asset = [AVURLAsset assetWithURL: url];
    _duration = CMTimeGetSeconds(asset.duration);
    NSLog(@"%f",_duration);

 

posted @ 2018-08-03 10:11  Mac开发小能手  阅读(494)  评论(0)    收藏  举报