iPhone: get duration of an audio file

2020-03-01 20:09发布

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.

8条回答
成全新的幸福
2楼-- · 2020-03-01 20:31

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.

查看更多
ら.Afraid
3楼-- · 2020-03-01 20:31

Combining AVAudioPlayer with Swift becomes as easy as (I am migrating a Realm table below, but you get the idea):

import AVFoundation

let resource = old!["filename"] as? String
let afUrl = NSBundle.mainBundle().URLForResource(resource, withExtension: nil)
let player = try! AVAudioPlayer(contentsOfURL: afUrl!)

new!["duration"] = Double(player.duration)
查看更多
相关推荐>>
4楼-- · 2020-03-01 20:31

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

查看更多
聊天终结者
5楼-- · 2020-03-01 20:37
 AVURLAsset* audioAsset = [AVURLAsset URLAssetWithURL:mp3_url options:nil];
                    [audioAsset loadValuesAsynchronouslyForKeys:@[@"duration"] completionHandler:^{
                        CMTime audioDuration = audioAsset.duration;
                        float audioDurationSeconds = CMTimeGetSeconds(audioDuration);

                        NSLog(@"duration:%f",audioDurationSeconds);
                    }];
查看更多
Anthone
6楼-- · 2020-03-01 20:39

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

查看更多
仙女界的扛把子
7楼-- · 2020-03-01 20:52

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

查看更多
登录 后发表回答