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.
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.
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.
Combining AVAudioPlayer with Swift becomes as easy as (I am migrating a Realm table below, but you get the idea):
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);
You can use the Audio File Services functions. There's one property to get that should give you the estimated duration. Code:
You can check the docs here
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))