views:

401

answers:

4

Hi,

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.

A: 

If you know anything about the audio file in question (samplerate, bitdepth, channel count), and it's an uncompressed format (WAV/AIFF), then you can calculate the /approximate/ duration from the filesize:

length_in_seconds = (file_length-guess_100_bytes_for_header) / (samplerate*(bitdepth*channel_count/8))

Dave Gamble
100 bytes for the header? Whatever happened to the canonical 44? :)
MusiGenesis
Any number of reasons ;) BWF metadata, AIFF header?
Dave Gamble
I should know better after 14 years of this, but just last month I spent half a day trying to figure out where the little click at the beginning of my sound was coming from. I was using my quick-and-dirty method that assumed just the 44 byte header. I learned my lesson, yet again.
MusiGenesis
A: 

It depends on the file type. If it's a WAV file you can locate the file's header and determine the playback duration that way. If it's a compressed format (*.mp3 etc.) you're better off sticking to the method you mentioned.

MusiGenesis
+2  A: 

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);
    UInt64 outDataSize = 0;
    UInt32 thePropSize = sizeof(UInt64);
    result = AudioFileGetProperty(fileID, kAudioFilePropertyEstimatedDuration, &thePropSize, &outDataSize);
    AudioFileClose(fileID);

You can check the docs here

pgb
Thanks, but I don't understand, why do I get every time that outDataSize equals to 0?
Ilya
Thank you for your solution, I found out where the problem was.
Ilya
Hey, that's not fair at all, using actual knowledge to get the check, instead of vague speculation about an OS you've never even worked with. :)
MusiGenesis
@Ilya: Glad it worked!@MusiGenesis: I have to use actual knowledge on some answer!
pgb
+1  A: 

Hi,

I am also using kAudioFilePropertyEstimatedDuration property to get duration . but in what format it will give duration. ?? and in which parameter it will give output. ?

NSURL *afUrl = [NSURL fileURLWithPath:soundPath];
AudioFileID fileID;
OSStatus result = AudioFileOpenURL((CFURLRef)afUrl, kAudioFileReadPermission, 0, &fileID);
UInt64 outDataSize = 0;

UInt32 thePropSize = sizeof(UInt64);
result = AudioFileGetProperty(fileID, kAudioFilePropertyEstimatedDuration, &thePropSize, &outDataSize);
AudioFileClose(fileID);

I will get outDataSize for duration but it is giving big value. I want to know in which format it is giving me duration and how can I convert that into Seconds. ?

Thanks in advance

mitul shah