Cocoa touch 使用iOS修剪音频

Cocoa touch 使用iOS修剪音频,cocoa-touch,audio,core-audio,trim,Cocoa Touch,Audio,Core Audio,Trim,我想实现一个功能,允许用户修剪他录制的音频文件(.caf)。录音部分已经可以工作了,但是我如何添加一个类似Voicememos应用程序中的微调功能呢。苹果使用的音频微调器有api吗? 任何帮助都很好…使用AVFoundation怎么样?将音频文件导入AVAsset(合成等),然后您可以将其导出到文件中(设置首选时间+持续时间) 我不久前写了一个stock函数,它将资产导出到文件中,您还可以指定audiomix。如下所示,它导出所有文件,但您可以将NSTimeRange添加到exporter.ti

我想实现一个功能,允许用户修剪他录制的音频文件(.caf)。录音部分已经可以工作了,但是我如何添加一个类似Voicememos应用程序中的微调功能呢。苹果使用的音频微调器有api吗?
任何帮助都很好…

使用AVFoundation怎么样?将音频文件导入AVAsset(合成等),然后您可以将其导出到文件中(设置首选时间+持续时间)

我不久前写了一个stock函数,它将资产导出到文件中,您还可以指定audiomix。如下所示,它导出所有文件,但您可以将NSTimeRange添加到exporter.timeRange,然后就可以了。虽然我还没有测试过,但应该有效(?)。另一种选择是在创建AVAsset+轨迹时调整时间范围。当然,出口商只处理m4a(AAC)。如果这不是你想要的,很抱歉

-(void)exportAsset:(AVAsset*)asset toFile:(NSString*)filename overwrite:(BOOL)overwrite withMix:(AVAudioMix*)mix {
//NSArray* availablePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:asset];

AVAssetExportSession* exporter = [AVAssetExportSession exportSessionWithAsset:asset presetName:AVAssetExportPresetAppleM4A];

if (exporter == nil) {
    DLog(@"Failed creating exporter!");
    return;
}

DLog(@"Created exporter! %@", exporter);

// Set output file type
DLog(@"Supported file types: %@", exporter.supportedFileTypes);
for (NSString* filetype in exporter.supportedFileTypes) {
    if ([filetype isEqualToString:AVFileTypeAppleM4A]) {
        exporter.outputFileType = AVFileTypeAppleM4A;
        break;
    }
}
if (exporter.outputFileType == nil) {
    DLog(@"Needed output file type not found? (%@)", AVFileTypeAppleM4A);
    return;
}

// Set outputURL
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* parentDir = [NSString stringWithFormat:@"%@/", [paths objectAtIndex:0]];

NSString* outPath = [NSString stringWithFormat:@"%@%@", parentDir, filename];

NSFileManager* manager = [NSFileManager defaultManager];
if ([manager fileExistsAtPath:outPath]) {
    DLog(@"%@ already exists!", outPath);
    if (!overwrite) {
        DLog(@"Not overwriting, uh oh!");
        return;
    }
    else {
        // Overwrite
        DLog(@"Overwrite! (delete first)");
        NSError* error = nil;
        if (![manager removeItemAtPath:outPath error:&error]) {
            DLog(@"Failed removing %@, error: %@", outPath, error.description);
            return;
        }
        else {
            DLog(@"Removed %@", outPath);
        }
    }
}

NSURL* const outUrl = [NSURL fileURLWithPath:outPath];
exporter.outputURL = outUrl;
// Specify a time range in case only part of file should be exported
//exporter.timeRange =

if (mix != nil)
    exporter.audioMix = mix; // important

DLog(@"Starting export! (%@)", exporter.outputURL);
[exporter exportAsynchronouslyWithCompletionHandler:^(void) {
    // Export ended for some reason. Check in status
    NSString* message;
    switch (exporter.status) {
        case AVAssetExportSessionStatusFailed:
            message = [NSString stringWithFormat:@"Export failed. Error: %@", exporter.error.description];
            DLog(@"%@", message);
            [self showAlert:message];
            break;
        case AVAssetExportSessionStatusCompleted: {
            /*if (playfileWhenExportFinished) {
             DLog(@"playfileWhenExportFinished!");
             [self playfileAfterExport:exporter.outputURL];
             playfileWhenExportFinished = NO;
             }*/
            message = [NSString stringWithFormat:@"Export completed: %@", filename];
            DLog(@"%@", message);
            [self showAlert:message];
            break;
        }
        case AVAssetExportSessionStatusCancelled:
            message = [NSString stringWithFormat:@"Export cancelled!"];
            DLog(@"%@", message);
            [self showAlert:message];
            break;
        default:
            DLog(@"Export unhandled status: %d", exporter.status);
            break;
    }       
}];
}

以上@Jonny的答案是正确的。在这里,我添加了AudioMixer的使用,以添加音频修剪时的淡入效果

输出:音频资源修剪为20秒,淡入10秒。 在代码段中设置的修剪在30秒时发生 资产的标记,因此跟踪持续时间应至少为 50秒

-(BOOL)exportAssettoFilePath:(NSString*)文件路径{
NSString*inputFilePath=;
NSURL*videoToTrimURL=[NSURL fileURLWithPath:inputFilePath];
AVAsset*AVAsset=[AVAsset AssetWithur:videoToTrimURL];
//对于这个片段,我们需要音频资源至少有50秒长
CMTime assetTime=[avAsset duration];
Float64持续时间=CMTimeGetSeconds(assetTime);
如果(持续时间<50.0)返回否;
//获取第一个音频曲目
NSArray*曲目=[avAsset tracks SwithMediaType:AVMediaTypeAudio];
如果([tracks count]==0)返回否;
AVAssetTrack*track=[tracks objectAtIndex:0];
//创建导出会话
//此处无需保留,会话将由
//完成处理程序,因为它在那里被引用
AVAssetExportSession*exportSession=[AVAssetExportSession
exportSessionWithAsset:avAsset
预设名称:AVAssetExportPresetAppleM4A];
if(nil==exportSession)返回NO;
//创建修剪时间范围-从30秒开始到资源中的20秒
CMTime startTime=CMTimeMake(30,1);
CMTime stopTime=CMTimeMake(50,1);
CMTimeRange exportTimeRange=CMTimeRangeFromTimeToTime(开始时间、停止时间);
//创建淡入时间范围-从修剪后的资源开始10秒
CMTime startFadeInTime=开始时间;
CMTime endFadeInTime=CMTimeMake(40,1);
CMTimeRange fadeInTimeRange=CMTimeRangeFromTimeToTime(startFadeInTime,
endFadeInTime);
//设置音频混音
AVMutableAudioMix*exportAudioMix=[AVMutableAudioMix audioMix];
AVMutableAudioMixInputParameters*exportAudioMixInputParameters=
[AVMutableAudioMixInputParameters AudioMixInputParameters SwithTrack:track];
[exportAudioMixInputParameters setVolumeRampFromStartVolume:0.0到EndVolume:1.0
时间范围:fadeInTimeRange];
exportAudioMix.inputParameters=[NSArray
arrayWithObject:exportAudioMixInputParameters];
//使用所有参数配置导出会话输出
exportSession.outputURL=[NSURL fileURLWithPath:filePath];//输出路径
exportSession.outputFileType=AVFileTypeAppleM4A;//输出文件类型
exportSession.timeRange=exportTimeRange;//修剪时间范围
//exportSession.audioMix=exportAudioMix;//淡入音频混合
//执行导出
[exportSession exportAsynchronouslyWithCompletionHandler:^{
if(AVAssetExportSessionStatusCompleted==exportSession.status){
NSLog(“AVAssetExportSessionStatusCompleted”);
}else if(AVAssetExportSessionStatusFailed==exportSession.status){
//由于您无法控制的事件,可能会发生故障
//例如,一个像电话一样的中断即将到来
//确保并妥善处理此案例
NSLog(@“AVAssetExportSessionStatusFailed”);
}否则{
NSLog(@“导出会话状态:%ld”,(长)exportSession.Status);
}
}];
返回YES;}

谢谢

有关详细信息:


但这种方法只允许声音以m4a格式保存,如果您想修剪mp3或caf文件并保持格式,该怎么办?修剪mp3也可以工作,输出以m4a格式存储2年后,您仍然可以救我的命:)如果有人在swift 4中查找答案,请查看以下链接:
- (BOOL)exportAssettoFilePath:(NSString *)filePath {


NSString *inputFilePath = <inputFilePath>;

NSURL *videoToTrimURL = [NSURL fileURLWithPath:inputFilePath];
AVAsset *avAsset = [AVAsset assetWithURL:videoToTrimURL];

// we need the audio asset to be at least 50 seconds long for this snippet
CMTime assetTime = [avAsset duration];
Float64 duration = CMTimeGetSeconds(assetTime);
if (duration < 50.0) return NO;

// get the first audio track
NSArray *tracks = [avAsset tracksWithMediaType:AVMediaTypeAudio];
if ([tracks count] == 0) return NO;

AVAssetTrack *track = [tracks objectAtIndex:0];

// create the export session
// no need for a retain here, the session will be retained by the
// completion handler since it is referenced there
AVAssetExportSession *exportSession = [AVAssetExportSession
                                       exportSessionWithAsset:avAsset
                                       presetName:AVAssetExportPresetAppleM4A];
if (nil == exportSession) return NO;

// create trim time range - 20 seconds starting from 30 seconds into the asset
CMTime startTime = CMTimeMake(30, 1);
CMTime stopTime = CMTimeMake(50, 1);
CMTimeRange exportTimeRange = CMTimeRangeFromTimeToTime(startTime, stopTime);

// create fade in time range - 10 seconds starting at the beginning of trimmed asset
CMTime startFadeInTime = startTime;
CMTime endFadeInTime = CMTimeMake(40, 1);
CMTimeRange fadeInTimeRange = CMTimeRangeFromTimeToTime(startFadeInTime,
                                                        endFadeInTime);

// setup audio mix
AVMutableAudioMix *exportAudioMix = [AVMutableAudioMix audioMix];
AVMutableAudioMixInputParameters *exportAudioMixInputParameters =
[AVMutableAudioMixInputParameters audioMixInputParametersWithTrack:track];

[exportAudioMixInputParameters setVolumeRampFromStartVolume:0.0 toEndVolume:1.0
                                                  timeRange:fadeInTimeRange];
exportAudioMix.inputParameters = [NSArray
                                  arrayWithObject:exportAudioMixInputParameters];

// configure export session  output with all our parameters
exportSession.outputURL = [NSURL fileURLWithPath:filePath]; // output path
exportSession.outputFileType = AVFileTypeAppleM4A; // output file type
exportSession.timeRange = exportTimeRange; // trim time range
//exportSession.audioMix = exportAudioMix; // fade in audio mix

// perform the export
[exportSession exportAsynchronouslyWithCompletionHandler:^{

    if (AVAssetExportSessionStatusCompleted == exportSession.status) {
        NSLog(@"AVAssetExportSessionStatusCompleted");
    } else if (AVAssetExportSessionStatusFailed == exportSession.status) {
        // a failure may happen because of an event out of your control
        // for example, an interruption like a phone call comming in
        // make sure and handle this case appropriately
        NSLog(@"AVAssetExportSessionStatusFailed");
    } else {
        NSLog(@"Export Session Status: %ld", (long)exportSession.status);
    }
}];

return YES;}