如何使用AVAssetReader和AVAssetWriter创建AAC文件?

时间:2011-12-18 13:44:40

标签: iphone ios

大家好! 我正在处理一个应用程序。它可以录制音频文件和邮件给其他人。音频文件保存为(.aac)文件。然后我想继续录制我已经保存为.aac文件。所以我用过AVAssetReader和AVAssetWriter使它成为现实。但我失败了!以下是我的代码:

AVMutableComposition *mixComposition = [AVMutableComposition composition];
NSURL *url = [NSURL fileURLWithPath:[DOCUMENTS_FOLDER stringByAppendingPathComponent:buttonTitle]];
NSURL *anotherUrl = [NSURL fileURLWithPath:[DOCUMENTS_FOLDER stringByAppendingPathComponent:[fileList objectAtIndex:0]]];


CMTime nextClipStartTime = kCMTimeZero;
AVURLAsset *preAudioAsset = [[AVURLAsset alloc]initWithURL:url options:nil];
CMTimeRange preTimeRange = CMTimeRangeMake(kCMTimeZero, preAudioAsset.duration);
AVMutableCompositionTrack *preCompositonTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
[preCompositonTrack insertTimeRange:preTimeRange ofTrack:[[preAudioAsset tracksWithMediaType:AVMediaTypeAudio]objectAtIndex:0] atTime:nextClipStartTime error:nil];

nextClipStartTime = CMTimeAdd(nextClipStartTime, preAudioAsset.duration);
AVURLAsset *cruAudioAsset = [[AVURLAsset alloc]initWithURL:anotherUrl options:nil];
CMTimeRange cruTimeRange = CMTimeRangeMake(kCMTimeZero, cruAudioAsset.duration);
[preCompositonTrack insertTimeRange:cruTimeRange ofTrack:[[cruAudioAsset tracksWithMediaType:AVMediaTypeAudio]objectAtIndex:0] atTime:nextClipStartTime error:nil];

//AVAssetReader part
NSError *error;
AVAssetReader *assetReader = [[AVAssetReader assetReaderWithAsset:mixComposition error:&error]retain];
if(error)
{
    NSLog(@"error:%@",error);

}
AVAssetTrack *audioTrack = [[mixComposition.tracks objectAtIndex:0]retain];
AVAssetReaderOutput *assetReaderOutput =[[AVAssetReaderTrackOutput assetReaderTrackOutputWithTrack:audioTrack outputSettings:nil]retain];
if(![assetReader canAddOutput:assetReaderOutput])
{
    NSLog(@"Can't add output!");
    return;
}
[assetReader addOutput:assetReaderOutput];

NSURL *exportUrl = [NSURL fileURLWithPath:[DOCUMENTS_FOLDER stringByAppendingPathComponent:@"combine.aac"]];

//AVAssetWriter part
AVAssetWriter *assetWriter = [[AVAssetWriter assetWriterWithURL:exportUrl fileType:AVFileTypeMPEG4 error:&error]retain];
if(error)
{
    NSLog(@"error:%@",error);
    return;
}
AudioChannelLayout channelLayout;
memset(&channelLayout, 0, sizeof(AudioChannelLayout));
channelLayout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
NSDictionary *outputSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                                [ NSNumber numberWithInt: kAudioFormatMPEG4AAC], AVFormatIDKey,
                                [ NSNumber numberWithInt: 1 ], AVNumberOfChannelsKey,
                                [ NSNumber numberWithFloat: 44100.0 ], AVSampleRateKey,
                                [ NSData dataWithBytes: &channelLayout length: sizeof( AudioChannelLayout ) ], AVChannelLayoutKey,
                                [ NSNumber numberWithInt: 64000 ], AVEncoderBitRateKey,
                                nil];
AVAssetWriterInput *assetWriterInput = [[AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeAudio outputSettings:outputSettings]retain];
if([assetWriter canAddInput:assetWriterInput])
{
    [assetWriter addInput:assetWriterInput];
}
else
{
    NSLog(@"can't add asset writer input .....");
    return;
}
assetWriterInput.expectsMediaDataInRealTime = NO;
[assetWriter startWriting];
[assetReader startReading];
CMTime startTime = CMTimeMake(0, audioTrack.naturalTimeScale);
[assetWriter startSessionAtSourceTime:startTime];

dispatch_queue_t mediaInputQueue = dispatch_queue_create("mediaInputQueue",NULL);
[assetWriterInput requestMediaDataWhenReadyOnQueue:mediaInputQueue usingBlock:^ {
    while(assetWriterInput.readyForMoreMediaData)
    {
        CMSampleBufferRef nextBuffer = [assetReaderOutput copyNextSampleBuffer];
        if(nextBuffer)
        {
            //append buffer
            [assetWriterInput appendSampleBuffer:nextBuffer];

        }
        else
        {
            [assetWriterInput markAsFinished];
            [assetWriter finishWriting];
            [assetReader cancelReading];
            [assetReader release];
            [assetReaderOutput release];
            [assetWriter release];
            [assetWriterInput release];
            break;
        }
    }
} ];

我只想记录另一个文件,然后将后一个文件附加到上一个文件,但是有一个错误: - [AVAssetWriterInput appendSampleBuffer:]输出缓冲区必须是线性PCM格式,当outputSettings不是nil'时

我想问一下我采取的方法是对的吗?如果我把它变成PCM格式(.wav)它很好,但录制文件的大小太大。如何解决提到的错误。我怎么能 通过代码将.wav转换为.aac文件?帮助!

1 个答案:

答案 0 :(得分:1)

尝试使用以下自定义设置初始化AVAssetReaderOutput

NSDictionary *settings =
    [NSDictionary dictionaryWithObjectsAndKeys:
     [NSNumber numberWithInt:kAudioFormatLinearPCM], AVFormatIDKey,
     [NSNumber numberWithFloat:44100.0], AVSampleRateKey,
     [NSNumber numberWithInt:16], AVLinearPCMBitDepthKey,
     [NSNumber numberWithBool:NO], AVLinearPCMIsNonInterleaved,
     [NSNumber numberWithBool:NO],AVLinearPCMIsFloatKey,
     [NSNumber numberWithBool:NO], AVLinearPCMIsBigEndianKey,
     nil];