连接两个.caf文件时,采样率发生了变化

时间:2015-04-08 05:58:10

标签: ios objective-c iphone ios8 avaudioplayer

我连接两个.caf文件, 首先我录制音频,然后录制另一个音频, 记录完成后,我连接这两个.caf文件的两个.caf采样率是16000赫兹,但是当连接最终.caf的采样率变为44100赫兹

我正在使用此代码

- (void)convertMP3WithFilePath:(NSString*)inputPath outputName:(NSString*)outputName {

_encodingStartInterval = [[NSDate date] timeIntervalSince1970] * 1000;
NSLog(@"Starting to convert file");

AVURLAsset * songAsset = [[AVURLAsset alloc] initWithURL:[NSURL fileURLWithPath:inputPath] options:nil];

NSError *assetError = nil;
AVAssetReader *assetReader = [[AVAssetReader assetReaderWithAsset:songAsset error:&assetError] retain];
if (assetError) {
    NSLog (@"error: %@", assetError);
    if (_delegate && [_delegate respondsToSelector:@selector(convertFailed:)]) {
        [_delegate performSelectorOnMainThread:@selector(convertFailed:) withObject:self waitUntilDone:NO];
    }
    return;
}

AVAssetReaderOutput *assetReaderOutput = [[AVAssetReaderAudioMixOutput assetReaderAudioMixOutputWithAudioTracks:
                                           songAsset.tracks audioSettings: nil] retain];
if (! [assetReader canAddOutput: assetReaderOutput]) {
    NSLog (@"can't add reader output... die!");
    if (_delegate && [_delegate respondsToSelector:@selector(convertFailed:)]) {
        [_delegate performSelectorOnMainThread:@selector(convertFailed:) withObject:self waitUntilDone:NO];
    }
    return;
}
[assetReader addOutput: assetReaderOutput];

float start = (_conversionStartPoint <= 0.0) ? 0.0 : _conversionStartPoint;
float length = (_conversionLength <= 0.0) ? CMTimeGetSeconds(songAsset.duration) : _conversionLength;


#ifdef DEMO
start = 0.0;
if (length > 10.0) length = 10.0;
#endif

CMTime startTrimTime = CMTimeMakeWithSeconds(start, 1);
CMTime endTrimTime = CMTimeMakeWithSeconds(start+length, 1);
CMTimeRange exportTimeRange = CMTimeRangeFromTimeToTime(startTrimTime, endTrimTime);
assetReader.timeRange = exportTimeRange;

NSString *tmpDir = [NSHomeDirectory() stringByAppendingPathComponent:@"tmp/"];
NSString *exportPath = [[tmpDir stringByAppendingPathComponent:@"temp.caf"] retain];

if ([[NSFileManager defaultManager] fileExistsAtPath:exportPath]) {
    [[NSFileManager defaultManager] removeItemAtPath:exportPath error:nil];
}

NSURL *exportURL = [NSURL fileURLWithPath:exportPath];
AVAssetWriter *assetWriter = [[AVAssetWriter assetWriterWithURL:exportURL
                                                       fileType:AVFileTypeCoreAudioFormat error:&assetError] retain];
if (assetError) {
    NSLog (@"error: %@", assetError);
    if (_delegate && [_delegate respondsToSelector:@selector(convertFailed:)]) {
        [_delegate performSelectorOnMainThread:@selector(convertFailed:) withObject:self waitUntilDone:NO];
    }
    return;
}
AudioChannelLayout channelLayout;
memset(&channelLayout, 0, sizeof(AudioChannelLayout));
channelLayout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
NSDictionary *outputSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                                [NSNumber numberWithInt:kAudioFormatLinearPCM], AVFormatIDKey,
                                [NSNumber numberWithFloat:16000.0], AVSampleRateKey,
                                [NSNumber numberWithInt:2], AVNumberOfChannelsKey,
                                [NSData dataWithBytes:&channelLayout length:sizeof(AudioChannelLayout)], AVChannelLayoutKey,
                                [NSNumber numberWithInt:16], AVLinearPCMBitDepthKey,
                                [NSNumber numberWithBool:NO], AVLinearPCMIsNonInterleaved,
                                [NSNumber numberWithBool:NO],AVLinearPCMIsFloatKey,
                                [NSNumber numberWithBool:NO], AVLinearPCMIsBigEndianKey,
                                nil];
AVAssetWriterInput *assetWriterInput = [[AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeAudio
                                                                           outputSettings:outputSettings]
                                        retain];
if ([assetWriter canAddInput:assetWriterInput]) {
    [assetWriter addInput:assetWriterInput];
} else {
    NSLog (@"can't add asset writer input... die!");
    if (_delegate && [_delegate respondsToSelector:@selector(convertFailed:)]) {
        [_delegate performSelectorOnMainThread:@selector(convertFailed:) withObject:self waitUntilDone:NO];
    }
    return;
}

assetWriterInput.expectsMediaDataInRealTime = NO;

[assetWriter startWriting];
[assetReader startReading];

AVAssetTrack *soundTrack = [songAsset.tracks objectAtIndex:0];
CMTime startTime = CMTimeMake (0, soundTrack.naturalTimeScale);



[assetWriter startSessionAtSourceTime: startTime];

__block UInt64 convertedByteCount = 0;

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];
             convertedByteCount += CMSampleBufferGetTotalSampleSize (nextBuffer);
             //NSLog (@"appended a buffer (%zd bytes)", CMSampleBufferGetTotalSampleSize (nextBuffer));
             convertedByteCount += CMSampleBufferGetTotalSampleSize (nextBuffer);
             //NSLog (@"%lld bytes converted", convertedByteCount);
         } else {
             // done!
             [assetWriterInput markAsFinished];
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 60000
             if ([[[UIDevice currentDevice] systemVersion] compare:@"6.0" options:NSNumericSearch] != NSOrderedAscending) {
                 //running on iOS 6.0. or higher
                 [assetWriter finishWritingWithCompletionHandler:^{
                     [assetWriter release];
                     [assetWriterInput release];
                 }];
             } else {
                 [assetWriter finishWritingWithCompletionHandler:NULL];
                 [assetWriter release];
                 [assetWriterInput release];
             }
#else
             [assetWriter finishWriting];
             [assetWriter release];
             [assetWriterInput release];
#endif

             [assetReader cancelReading];
             NSDictionary *outputFileAttributes = [[NSFileManager defaultManager]
                                                   attributesOfItemAtPath:exportPath
                                                   error:nil];
             NSLog (@"Media is converted to WAV. File size is %lld",[outputFileAttributes fileSize]);
             _fileSize = [self encodeFileWithFilePath:exportPath outputName:outputName];

             if (!_fileSize) {
                 if (_delegate && [_delegate respondsToSelector:@selector(convertFailed:)]) {
                     [_delegate performSelectorOnMainThread:@selector(convertFailed:) withObject:self waitUntilDone:NO];
                 }
             } else {
                 _encodingEndInterval = [[NSDate date] timeIntervalSince1970] * 1000;
                 _elapsedTime = (long int) (_encodingEndInterval -_encodingStartInterval);

                 if (_delegate && [_delegate respondsToSelector:@selector(convertDone:)]) {
                     [_delegate performSelectorOnMainThread:@selector(convertDone:) withObject:self waitUntilDone:NO];
                 }
             }

             [assetReader release];
             [assetReaderOutput release];
             [exportPath release];

             break;
         }
     }

 }];
}

0 个答案:

没有答案