iphone - 来自 MPMediaItem 的 NSData

标签 iphone ios ipad

有人可以帮我如何将从设备媒体库中选择的歌曲转换为 NSData 吗? 我需要一个接受媒体项并返回该特定媒体项的 NSData 的函数。

提前致谢

最佳答案

您可以使用此代码

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);

关于iphone - 来自 MPMediaItem 的 NSData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18824983/

相关文章:

ios - 当前 View Controller 内的 subview 上未调用滑动手势

ios - 如何限制 iOS 应用仅适用于 iPhone,不包括 iPad?

iphone - 解析 RSS 提要 - 检索图像、URL?

ios - 无法将变量设置为 nil

ios - Webview景观

ios - iCloud 和核心数据。 NSFetchedResultsController 不会在初始同步时更新

ios - e :Core data self referential relationships lost after application relaunch

iphone - 如何在按下 UIBarButtonItem 之前启用/禁用方向(旋转)?

iphone - 如何从第二层向下建立 UINavigationController(不是从 Delegate/RootController 层)

ios - 移动浏览器上随机区域的随机数