2011-01-07 54 views
5

(Objective C) 只使用簡單的AudioServicesPlaySystemSoundID及其對應物,但在文檔中找不到已存在的方法來查找音頻文件的長度。如何查找音頻文件的長度(以秒爲單位)

我知道有AudioServicesGetPropertyInfo,但似乎返回一個字節緩衝區 - 做音頻文件嵌入自己的長度,我可以提取它與此?

或者有可能是一個公式基於比特率* fileSize轉換爲長度的時間?

mIL3S

www.milkdrinkingcow.com

回答

14

根據快速谷歌搜索,有一個公式:

length-of-time (duration in seconds) = fileSize (in bytes)/bit-rate (bits/secs)*8 

有你使用系統聲音服務於任何特別的理由播放聲音?

如果使用AVAudioPlayer來處理你的聲音,你可以這樣做:

AVAudioPlayer * sound = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:nil]; 
sound.delegate = self; 
sound.volume = 1; 
NSLog([NSString stringWithFormat:@"%f", sound.duration]); 
+0

雅,我想我應該只使用AVAudioPlayer。我想因爲我只是在播放一些小聲音,所以AudioServices還好;現在我需要更多的信息,我應該切換。儘管感謝您的公式!我雖然可能有這樣的事情。 mIL3S – 2011-01-07 23:04:43

11

來自a的示例代碼請撥打How to get the duration of an audio file in iOS?。這是最好的答案。

AVURLAsset* audioAsset = [AVURLAsset URLAssetWithURL:audioFileURL options:nil]; CMTime audioDuration = audioAsset.duration; float audioDurationSeconds = CMTimeGetSeconds(audioDuration);

+0

這是實現這個IMO的最佳通用方法。 – theLastNightTrain 2014-06-23 15:13:51

相關問題