How to find an audio file's length (in seconds)
Solution 1
According to a quick Google search, there is a formula:
length-of-time (duration in seconds) = fileSize (in bytes) / bit-rate (bits/secs)*8
Is there any particular reason you're using System Sound Services to play a sound?
If you use AVAudioPlayer to handle your sounds you could do something like:
AVAudioPlayer * sound = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:nil];
sound.delegate = self;
sound.volume = 1;
NSLog([NSString stringWithFormat:@"%f", sound.duration]);
Solution 2
sample code from answer How to get the duration of an audio file in iOS?. This is the best answer.
AVURLAsset* audioAsset = [AVURLAsset URLAssetWithURL:audioFileURL options:nil];
CMTime audioDuration = audioAsset.duration;
float audioDurationSeconds = CMTimeGetSeconds(audioDuration);
Related videos on Youtube
Miles Alden
Updated on May 15, 2022Comments
-
Miles Alden almost 2 years
(Objective C) Just using simple AudioServicesPlaySystemSoundID and its counterparts, but I can't find in the documentation if there is already a way to find the length of an audio file.
I know there is AudioServicesGetPropertyInfo, but that seems to return a byte-buffer - do audio files embed their length in themselves and I can just extract it with this?
Or is there perhaps a formula based on bit-rate * fileSize to convert to length-of-time?
mIL3S
www.milkdrinkingcow.com
-
Miles Alden over 13 yearsYa, I suppose I should just use AVAudioPlayer. I guess since I was just playing a few little sounds the AudioServices was okay; now that I need more info from it I should probably switch over. Thanks for the formula though! I though there might be something like that. mIL3S
-
newenglander almost 11 yearsBut isn't this only for Mac OS X? The question is tagged with iPhone.
-
theLastNightTrain almost 10 yearsThis is the best general way to achieve this IMO.