iPhone: get duration of an audio file

2020-03-01 20:09发布

What is the easiest way to get a duration of an audio file?

I could create an object of AVAudioPlayer, initialize it with URL and than get the duration, but this way is too long. Is there an easier way?

Thanks.

8条回答
劳资没心,怎么记你
2楼-- · 2020-03-01 20:54

In case anyone lands here looking for a way to get the duration for both audio and video files, have a look at this answer to another post, which instead uses AVAsset instead:

https://stackoverflow.com/a/7052147/381233

Using AudioFileGetProperty (like the other two main answers here) to get the duration of A/V files didn't work for a few .mov files on my device (result was always 0), while the solution using AVAsset got the duration for all audio and video files on my device.

(Interestingly enough, however, the duration from both solutions was sometimes 1 second more than that displayed in the UI of an actual AVAudioPlayer. Most likely the AVAudioPlayer uses a non-standard rounding routine for the displayed duration.)

查看更多
霸刀☆藐视天下
3楼-- · 2020-03-01 20:57

Correct code is

NSURL *afUrl = [NSURL fileURLWithPath:soundPath];
AudioFileID fileID;
OSStatus result = AudioFileOpenURL((CFURLRef)afUrl, kAudioFileReadPermission, 0, &fileID);
Float64 outDataSize = 0;
UInt32 thePropSize = sizeof(Float64);
result = AudioFileGetProperty(fileID, kAudioFilePropertyEstimatedDuration, &thePropSize, &outDataSize);
AudioFileClose(fileID);

outDataSize should be Float64 not UInt64.

查看更多
登录 后发表回答