这不是一项简单的任务 - Apple的SDK通常无法为简单任务提供简单的API。这是我在我的一个调整中使用的代码,以便从资产中获取原始PCM数据。你需要的AVFoundation和CoreMedia框架添加到项目中,为了得到这个工作:
#import <AVFoundation/AVFoundation.h>
#import <CoreMedia/CoreMedia.h>
MPMediaItem *item = // obtain the media item
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// Get raw PCM data from the track
NSURL *assetURL = [item valueForProperty:MPMediaItemPropertyAssetURL];
NSMutableData *data = [[NSMutableData alloc] init];
const uint32_t sampleRate = 16000; // 16k sample/sec
const uint16_t bitDepth = 16; // 16 bit/sample/channel
const uint16_t channels = 2; // 2 channel/sample (stereo)
NSDictionary *opts = [NSDictionary dictionary];
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:assetURL options:opts];
AVAssetReader *reader = [[AVAssetReader alloc] initWithAsset:asset error:NULL];
NSDictionary *settings = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:kAudioFormatLinearPCM], AVFormatIDKey,
[NSNumber numberWithFloat:(float)sampleRate], AVSampleRateKey,
[NSNumber numberWithInt:bitDepth], AVLinearPCMBitDepthKey,
[NSNumber numberWithBool:NO], AVLinearPCMIsNonInterleaved,
[NSNumber numberWithBool:NO], AVLinearPCMIsFloatKey,
[NSNumber numberWithBool:NO], AVLinearPCMIsBigEndianKey, nil];
AVAssetReaderTrackOutput *output = [[AVAssetReaderTrackOutput alloc] initWithTrack:[[asset tracks] objectAtIndex:0] outputSettings:settings];
[asset release];
[reader addOutput:output];
[reader startReading];
// read the samples from the asset and append them subsequently
while ([reader status] != AVAssetReaderStatusCompleted) {
CMSampleBufferRef buffer = [output copyNextSampleBuffer];
if (buffer == NULL) continue;
CMBlockBufferRef blockBuffer = CMSampleBufferGetDataBuffer(buffer);
size_t size = CMBlockBufferGetDataLength(blockBuffer);
uint8_t *outBytes = malloc(size);
CMBlockBufferCopyDataBytes(blockBuffer, 0, size, outBytes);
CMSampleBufferInvalidate(buffer);
CFRelease(buffer);
[data appendBytes:outBytes length:size];
free(outBytes);
}
[output release];
[reader release];
[pool release];
这里data
将包含曲目的原始PCM数据;你可以使用某种编码来压缩它,例如我使用FLAC编解码器库。
查看original source code here。
awesomely done111 – Kamarshad
此代码需要超过2秒的iPhone 4上的单个音频文件。有什么办法让这个文件读取更快? –
@iDev No. [15个字符] – 2013-05-14 11:07:31