Экспорт файлов Wav с помощью AVAssetExportSession

Я пытаюсь добавить затухание в файл wav, а затем экспортирую новый файл с добавленным затуханием, используя AVAssetExportSession. Все примеры, которые я видел, экспортируются как m4u. Возможно ли это сделать с помощью wav или aif?

Ошибка, которую я получаю:

AVAssetExportSessionStatusFailed Error Domain=AVFoundationErrorDomain Code=-11822 "Cannot Open" UserInfo=0x1f01c9f0 {NSLocalizedDescription=Cannot Open, NSLocalizedFailureReason=This media format is not supported.} 

Мой код выглядит следующим образом

 NSString *inpath = [path stringByAppendingFormat:@"/%@",file];

    NSString *ename = [file stringByDeletingPathExtension];
    NSString *incname = [ename stringByAppendingString:@"1t"];
    NSString *outname = [incname stringByAppendingPathExtension:@"wav"];
    NSString *outpath = [path stringByAppendingFormat:@"/%@",outname];

    NSURL *urlpath = [NSURL fileURLWithPath:inpath];
    NSURL *urlout = [NSURL fileURLWithPath:outpath];



    NSDictionary *options = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES]
                                                        forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
    AVURLAsset *anAsset = [[AVURLAsset alloc] initWithURL:urlpath options:options];


    //check the soundfile is greater than 50seconds
    CMTime assetTime = [anAsset duration];
    Float64 duration = CMTimeGetSeconds(assetTime);
    if (duration < 50.0) return NO;

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

    AVAssetTrack *track = [tracks objectAtIndex:0];

    // 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];

    AVAssetExportSession *exportSession = [AVAssetExportSession
                                           exportSessionWithAsset:anAsset presetName:AVAssetExportPresetPassthrough];


    //NSArray *listof = [AVAssetExportSession exportPresetsCompatibleWithAsset:anAsset];
    //NSLog(@"LISTOF %@",listof);

    id desc = [track.formatDescriptions objectAtIndex:0];
    const AudioStreamBasicDescription *audioDesc = CMAudioFormatDescriptionGetStreamBasicDescription((CMAudioFormatDescriptionRef)desc);
    FourCharCode formatID = audioDesc->mFormatID;

    NSString *fileType = nil;
    NSString *ex = nil;

    switch (formatID) {

        case kAudioFormatLinearPCM:
        {
            UInt32 flags = audioDesc->mFormatFlags;
            if (flags & kAudioFormatFlagIsBigEndian) {
                fileType = @"public.aiff-audio";
                ex = @"aif";
            } else {
                fileType = @"com.microsoft.waveform-audio";
                ex = @"wav";
            }
        }
            break;

        case kAudioFormatMPEGLayer3:
            fileType = @"com.apple.quicktime-movie";
            ex = @"mp3";
            break;

        case kAudioFormatMPEG4AAC:
            fileType = @"com.apple.m4a-audio";
            ex = @"m4a";
            break;

        case kAudioFormatAppleLossless:
            fileType = @"com.apple.m4a-audio";
            ex = @"m4a";
            break;

        default:
            break;
    }



    exportSession.outputFileType = fileType;
    exportSession.outputURL = urlout;

    //exportSession.outputFileType = AVFileTypeWAVE; // 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 %@",exportSession.error);
        } else {
            NSLog(@"Export Session Status: %d", exportSession.status);
        }
    }];

    return YES;
    }

person user1347149    schedule 29.04.2013    source источник
comment
О какой ОС вы говорите?   -  person El Tomato    schedule 29.04.2013
comment
Это для iOS версии 6   -  person user1347149    schedule 29.04.2013
comment
Вы решили свою проблему? Недавно я также ищу способ экспортировать файл wav.   -  person Allen Hsu    schedule 20.05.2013


Ответы (1)


Вы не можете сделать это с AVAssetExportSession, потому что пресеты довольно фиксированы в своем использовании. Предустановленное значение AVAssetExportPresetPassthrough сохранит ваши входные форматы на выходе.

Поскольку ваша задача будет напрямую манипулировать буферами аудиосэмплов, вам следует использовать второй вариант, который вам предоставит AVFoundation: парная установка AVAssetReader и AVAssetWriter. Вы найдете правильный пример кода, как в AVReaderWriterOSX, из источника Apple для разработчиков. Это также должно работать с iOS, кроме того, что у вас есть другие доступные настройки формата ввода-вывода. Должна быть предоставлена ​​возможность распаковывать аудио как PCM и записывать обратно в несжатый файл .wav.

person konran    schedule 05.06.2013