2012-10-30 33 views
2

我已經從我的iPhone設備中檢索到所有音樂和視頻。我現在堅持將它們保存到我的應用程序中,我無法從文件中獲取原始數據。任何人都可以幫助我找到解決方案。這是我用來獲取音樂文件的代碼。從iPhone中的音樂文件中獲取NSData

MPMediaQuery *deviceiPod = [[MPMediaQuery alloc] init]; 
NSArray *itemsFromGenericQuery = [deviceiPod items]; 
for (MPMediaItem *media in itemsFromGenericQuery){ 
//i get the media item here. 
} 

如何將其轉換爲NSData? 這就是我試圖讓數據

audioURL = [media valueForProperty:MPMediaItemPropertyAssetURL];//here i get the asset url 
NSData *soundData = [NSData dataWithContentsOfURL:audioURL]; 

使用,這是沒用的我。我不知道從LocalAssestURL得到的數據。任何解決方案。在此先感謝

回答

9

這不是一項簡單的任務 - 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

+2

awesomely done111 – Kamarshad

+0

此代碼需要超過2秒的iPhone 4上的單個音頻文件。有什麼辦法讓這個文件讀取更快? –

+1

@iDev No. [15個字符] – 2013-05-14 11:07:31