Search code examples
iphonecocoa-touch

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.


Solution

  • 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