-->

获取的NSData了音乐文件的iPhone(Getting NSData out of music

2019-08-02 02:49发布

我已经检索到的所有的音乐和视频从我的iPhone设备。 现在我被困在拯救那些在我的应用程序,我无法获取原始数据出来的文件。 任何一个可以帮助我找到了一个解决方案。 这是我用来获取音乐文件的代码。

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 。 这方面的任何解决方案。 提前致谢

Answer 1:

这不是一个简单的任务 - 苹果公司的软件开发工具包往往不能简单的任务提供了简单的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编解码器库。

看到这里原来的源代码 。



文章来源: Getting NSData out of music file in iPhone