#pragma mark - 截取音频方法
- (void)captureSongAction
{
CocoaSecurityResult * result = [CocoaSecurity md5:[[NSDate date] description]];
// 创建音频文件
NSArray *dirs = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask,YES);
NSString *documentsDirectoryPath = [dirs objectAtIndex:0];
NSString *filePath = [documentsDirectoryPath stringByAppendingPathComponent:@"CaptureMusic"];
if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
[[NSFileManager defaultManager] createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
}
NSString *tempMusicPath = [NSString stringWithFormat:@"%@/%@.m4a",filePath, result.hex];
NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:self.asset];
if ([compatiblePresets containsObject:AVAssetExportPresetMediumQuality]) {
AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]
initWithAsset:self.asset presetName:AVAssetExportPresetAppleM4A];
// Implementation continues.
CMTime startTime = CMTimeMake(self.startTime, 1);
CMTime stopTime = CMTimeMake(self.startTime+self.playTime, 1);
CMTimeRange exportTimeRange = CMTimeRangeFromTimeToTime(startTime, stopTime);
NSURL *furl = [NSURL fileURLWithPath:tempMusicPath];
exportSession.outputURL = furl;
exportSession.outputFileType = AVFileTypeAppleM4A;
exportSession.timeRange = exportTimeRange; // 截取时间
[exportSession exportAsynchronouslyWithCompletionHandler:^{
switch ([exportSession status]) {
case AVAssetExportSessionStatusFailed:
NSLog(@"Export failed: %@", [[exportSession error] localizedDescription]);
break;
case AVAssetExportSessionStatusCancelled:
NSLog(@"Export canceled");
break;
default:
[self addCertainAlertViewWithTitle:LocalizedString(@"AlertViewTitleSysPrompt") Message:@"截取成功"];
NSLog(@"保存成功");
}
}];
}
}
因为iOS的输出格式不支持.mp3,只能设置为.m4a的音频文件.
AVAssetExportSession支持导出的文件类型如下所示:
<__NSArrayI 0x158c0d60>(
com.apple.quicktime-movie,
com.apple.m4a-audio,
public.mpeg-4,
com.apple.m4v-video,
public.3gpp,
org.3gpp.adaptive-multi-rate-audio,
com.microsoft.waveform-audio,
public.aiff-audio,
public.aifc-audio,
com.apple.coreaudio-format
)