Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone: get duration of an audio file

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.

like image 306
Ilya Suzdalnitski Avatar asked Aug 07 '09 19:08

Ilya Suzdalnitski


2 Answers

You can use the Audio File Services functions. There's one property to get that should give you the estimated duration. Code:

    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);

You can check the docs here

like image 74
pgb Avatar answered Sep 30 '22 03:09

pgb


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.

like image 31
Farhad Malekpour Avatar answered Sep 30 '22 04:09

Farhad Malekpour