在线播放音频
参考连接:http://msching.github.io/blog/2014/07/09/audio-in-ios-3/
计算总时长
计算时长Duration
获取时长的最佳方法是从ID3信息中去读取,那样是最准确的。如果ID3信息中没有存,那就依赖于文件头中的信息去计算了。
计算duration的公式如下:
1
double duration = (audioDataByteCount * 8) / bitRate
音频数据的字节总量audioDataByteCount可以通过kAudioFileStreamProperty_AudioDataByteCount获取,码率bitRate可以通过kAudioFileStreamProperty_BitRate获取也可以通过Parse一部分数据后计算平均码率来得到。
对于CBR数据来说用这样的计算方法的duration会比较准确,对于VBR数据就不好说了。所以对于VBR数据来说,最好是能够从ID3信息中获取到duration,获取不到再想办法通过计算平均码率的途径来计算duration。
获取ID3信息:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28- (void)getDurationWithCompletion:(void(^)(NSTimeInterval duration))comp {
NSDictionary *options = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
AVURLAsset *audioAsset = [[[AVURLAsset alloc] initWithURL:_url options:options] autorelease];
NSArray *keys = [[NSArray alloc] initWithObjects:@"duration", nil];
[audioAsset loadValuesAsynchronouslyForKeys:keys completionHandler:^{
NSError *error = nil;
switch ([audioAsset statusOfValueForKey:@"duration" error:&error]) {
case AVKeyValueStatusLoaded:{
CMTime audioDuration = audioAsset.duration;
NSTimeInterval duration = CMTimeGetSeconds(audioDuration);
if (comp) {
dispatch_async(dispatch_get_main_queue(),^{
comp(duration);
});
}
}
// duration is now known, so we can fetch it without blocking
// CMTime duration = [asset duration];
// dispatch a block to the main thread that updates the display of asset duration in my user interface,
// or do something else interesting with it
default: ;
// something went wrong; depending on what it was, we may want to dispatch a
// block to the main thread to report th e error
}
}];
}