如何通过AVAssetReader读取音频样本?我已经找到了使用AVAssetReader进行复制或混合的示例,但是这些循环始终由AVAssetWriter循环控制。是否可以仅创建一个AVAssetReader并通过它阅读,获取每个样本并将每个音频样本的int32放入数组中?
谢谢。
如何通过AVAssetReader读取音频样本?我已经找到了使用AVAssetReader进行复制或混合的示例,但是这些循环始终由AVAssetWriter循环控制。是否可以仅创建一个AVAssetReader并通过它阅读,获取每个样本并将每个音频样本的int32放入数组中?
谢谢。
为了进一步解释@amrox的答案,你可以从CMBlockBufferRef获取一个AudioBufferList,例如:
CMItemCount numSamplesInBuffer = CMSampleBufferGetNumSamples(buffer);
AudioBufferList audioBufferList;
CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(
buffer,
NULL,
&audioBufferList,
sizeof(audioBufferList),
NULL,
NULL,
kCMSampleBufferFlag_AudioBufferList_Assure16ByteAlignment,
&buffer
);
for (int bufferCount=0; bufferCount < audioBufferList.mNumberBuffers; bufferCount++) {
SInt16* samples = (SInt16 *)audioBufferList.mBuffers[bufferCount].mData;
for (int i=0; i < numSamplesInBuffer; i++) {
// amplitude for the sample is samples[i], assuming you have linear pcm to start with
}
}
//Release the buffer when done with the samples
//(retained by CMSampleBufferGetAudioBufferListWithRetainedblockBuffer)
CFRelease(buffer);
AVAssetReader *reader = [[AVAssetReader alloc] initWithAsset:asset error:&error];
AVAssetTrack *track = [[asset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0];
NSDictionary *settings = @{ AVFormatIDKey : [NSNumber numberWithInt:kAudioFormatLinearPCM] };
AVAssetReaderTrackOutput *readerOutput = [AVAssetReaderTrackOutput assetReaderTrackOutputWithTrack:track
outputSettings:settings];
[reader addOutput:readerOutput];
[reader startReading];
CMSampleBufferRef sample = [readerOutput copyNextSampleBuffer];
while ( sample )
{
sample = [readerOutput copyNextSampleBuffer];
if ( ! sample )
{
continue;
}
CMBlockBufferRef buffer = CMSampleBufferGetDataBuffer(sample);
size_t lengthAtOffset;
size_t totalLength;
char *data;
if ( CMBlockBufferGetDataPointer( buffer, 0, &lengthAtOffset, &totalLength, &data ) != noErr )
{
NSLog(@"error!");
break;
}
// do something with data...
CFRelease(sample);
}
AudioBufferList
的大小时,调用CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer
可能会失败,例如在使用非交错样本时。CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer
两次。第一次调用查询所需的AudioBufferList
大小,第二次调用填充实际的AudioBufferList
。size_t bufferSize = 0;
CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(
sampleBuffer,
&bufferSize,
NULL,
0,
NULL,
NULL,
0,
NULL
);
AudioBufferList *bufferList = malloc(bufferSize);
CMBlockBufferRef blockBuffer = NULL;
CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(
sampleBuffer,
NULL,
bufferList,
bufferSize,
NULL,
NULL,
kCMSampleBufferFlag_AudioBufferList_Assure16ByteAlignment,
&blockBuffer
);
// handle audio here
free(bufferList);
CFRelease(blockBuffer);
AudioBufferList
。
samples[i] *= 0.5;
之类的音量调整操作时一切正常。有什么原因吗? - Dex