美文网首页
获取aac格式音频时长不准确的问题

获取aac格式音频时长不准确的问题

作者: wuyukobe | 来源:发表于2019-08-04 21:01 被阅读0次

    最近遇到了一个问题,大致就是用如下的方法获取一段aac格式的音频url时长会不准确,就是每次获取的时长都不一样,而获取的mp3格式的音频url时长就没问题,感到很奇怪。

    /**
     获取音频时长
     
     @param  audioURL 音频URL
     @return 音频时长
     */
    + (CGFloat)getAudioDurationWithAudioURL:(NSURL *)audioURL
    {
        NSDictionary *opts = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO]
                                                         forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
        AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:audioURL options:opts];
        CGFloat second = urlAsset.duration.value * 1.0 / urlAsset.duration.timescale;
        return second;
    }
    

    然后就查了一下方法中一个AVURLAssetPreferPreciseDurationAndTimingKey参数设置意思,其中源码中有这样一段注释:

    If nil is passed as the value of the options parameter to -[AVURLAsset initWithURL:options:], or if a dictionary that lacks a value for the key AVURLAssetPreferPreciseDurationAndTimingKey is passed instead, a default value of NO is assumed. If the asset is intended to be played only, because AVPlayer will support approximate random access by time when full precision isn't available, the default value of NO will suffice.
       Pass YES if longer loading times are acceptable in cases in which precise timing is required. If the asset is intended to be inserted into an AVMutableComposition, precise random access is typically desirable and the value of YES is recommended.
    

    意思就是AVURLAssetPreferPreciseDurationAndTimingKey参数默认设置为NO,如果仅仅只是播放,AVPlayer则会获取没有完全精度的近似时长,默认值NO就足够了。如果想要获取比较准确的时长则需要设置为YES,但这样有个问题就是加载时长相对长些。于是就明白了之前为什么会出现获取时长不准确这样的问题。然后就在原方法中修改默认值NO为YES,就解决了这个问题,毕竟我只是为了获取准确时长,并不需要播放。再次感受到了查看源码的重要性!

    相关文章

      网友评论

          本文标题:获取aac格式音频时长不准确的问题

          本文链接:https://www.haomeiwen.com/subject/qrtudctx.html