首先导入框架#import <AVFoundation/AVFoundation.h>
计算录音文件的时长
方法1:
//获取音频时长
AVURLAsset* audioAsset =[AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:path] options:nil];
CMTime audioDuration=audioAsset.duration;
//换成秒
float audioDurationSeconds = CMTimeGetSeconds(audioDuration);
方法2:
- (NSTimeInterval)audioDurationFromURL:(NSString *)url {
AVURLAsset *audioAsset = nil;
NSDictionary *dic = @{AVURLAssetPreferPreciseDurationAndTimingKey:@(YES)};
if ([url hasPrefix:@"http://"]|| [url hasPrefix:@"https://"]) {
audioAsset = [AVURLAsset URLAssetWithURL:[NSURL URLWithString:url] options:dic];
}else {
audioAsset = [AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:url] options:dic];
}
CMTime audioDuration = audioAsset.duration;
float audioDurationSeconds = CMTimeGetSeconds(audioDuration);
return audioDurationSeconds;
}
总结:其实两个方法核心都是一样的,只是多个属性AVURLAssetPreferPreciseDurationAndTimingKey,布尔类型,是否提供更精确的时长。两种方法获取的时长对比,如下图
音频的剪切和播放
/**
音频的剪切
@param audioPath 要剪切的音频路径
@param fromTime 开始剪切的时间点 (秒)
@param toTime 结束剪切的时间点 (秒)
@param outputPath 剪切成功后的音频路径
*/
-(void)cutAudio:(NSString *)audioPath fromTime:(NSTimeInterval)fromTime toTime:(NSTimeInterval)toTime outputPath:(NSString *)outputPath{
// 1. 获取音频源
AVURLAsset *asset = [AVURLAsset assetWithURL:[NSURL fileURLWithPath:audioPath]];
// 2. 创建一个音频会话, 并且,设置相应的配置
AVAssetExportSession *session = [AVAssetExportSession exportSessionWithAsset:asset presetName:AVAssetExportPresetAppleM4A];
session.outputFileType = AVFileTypeAppleM4A;
session.outputURL = [NSURL fileURLWithPath:outputPath];
CMTime startTime = CMTimeMake(fromTime, 1);
CMTime endTime = CMTimeMake(toTime, 1);
session.timeRange = CMTimeRangeFromTimeToTime(startTime, endTime);
// 3. 导出
[session exportAsynchronouslyWithCompletionHandler:^{
AVAssetExportSessionStatus status = session.status;
if (status == AVAssetExportSessionStatusCompleted)
{
NSLog(@"导出成功");
NSError*playerError;
NSURL *url = [NSURL fileURLWithPath:outputPath];
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&playerError];
[self.player setNumberOfLoops:0];// 设置播放循环次数
[self.player setVolume:1];// 音量,0-1之间
[self.player setDelegate:self];
// [self.player prepareToPlay];// 分配播放所需的资源,并将其加入内部播放队列
// [self.player play];// 开始播放
if (self.player)
{
if ([self.player prepareToPlay])
{
// 播放时,设置喇叭播放否则音量很小
AVAudioSession *playSession = [AVAudioSession sharedInstance];
[playSession setCategory:AVAudioSessionCategoryPlayback error:nil];
[playSession setActive:YES error:nil];
[self.player play];
}
}
}
}];
}