iOS读取itunes音乐
在项目中我们可能需要上传iPhone手机中的音乐到服务器。怎么上传?首先需要读区到音乐流,下面将介绍iOS读区iTunes音乐:
1. 跳转页面
如果是simulator是跳转不成功的(直接上代码)
if([model isEqualToString:@"iPhone Simulator"] == NO) {
MPMediaPickerController *pickController = [[MPMediaPickerController alloc] initWithMediaTypes:MPMediaTypeMusic];
[pickController setDelegate:self];
[self.tabbar presentViewController:pickController animated:YEScompletion:^{
}];
}
2. 选择歌曲
第一步过后会跳到你的音乐列表 当你选择某一个歌曲后会执行相应的代理方法
- mediaPicker: didPickMediaItems:
下面介绍如何将音乐读成NSData:
-(void)mediaPicker:(MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection{
MPMediaItem *selectedSongItem = [[mediaItemCollection items]objectAtIndex:0];
NSURL *songURL = [selectedSongItem valueForProperty:MPMediaItemPropertyAssetURL]; // 歌曲的URL通常为ipod-library://item/item.mp3?id=-7350999950458851124
NSString *songName = [selectedSongItem valueForProperty:MPMediaItemPropertyTitle]; // 歌曲的Title
//将页面关闭
[mediaPicker dismissViewControllerAnimated:YEScompletion:nil];
NSMutableData *songData;
NSInteger soundLength;
if (!songURL) {
MyLog(@"%@ has DRM",songName);
soundLength = 0;
} else {
AVURLAsset *songAsset = [AVURLAssetURL AssetWithURL:songURL options:nil];
// _soundUrl = songURL.absoluteString;
NSError * error = nil;
CMTime duration = songAsset.duration;
soundLength = (int)CMTimeGetSeconds(duration) / 1 + ((int)(CMTimeGetSeconds(duration)*10)!=0);
AVAssetReader * reader = [[AVAssetReader alloc] initWithAsset:songAsset error:&error];
AVAssetTrack * songTrack = [songAsset.tracks objectAtIndex:0];
AVAssetReaderTrackOutput * output = [[AVAssetReaderTrackOutput alloc]initWithTrack:songTrack outputSettings:nil];
[reader addOutput:output];
songData = [[NSMutableDataalloc] init];
[reader startReading];
while (reader.status == AVAssetReaderStatusReading) {
// AVAssetReaderTrackOutput method
AVAssetReaderTrackOutput * trackOutput = (AVAssetReaderTrackOutput*)[reader.outputs objectAtIndex:0];
CMSampleBufferRef sampleBufferRef = [trackOutput copyNextSampleBuffer];
if (sampleBufferRef){
CMBlockBufferRef blockBufferRef =CMSampleBufferGetDataBuffer(sampleBufferRef);
size_t length = CMBlockBufferGetDataLength(blockBufferRef);
UInt8 buffer[length];
CMBlockBufferCopyDataBytes(blockBufferRef, 0, length, buffer);
NSData *data = [[NSData alloc] initWithBytes:buffer length:length];
[songData appendData:data];
CMSampleBufferInvalidate(sampleBufferRef);
CFRelease(sampleBufferRef);
}
}
}
//这里你可以拿到songData后跳到你想要的页面或者是上传服务器等操作
}
至此将iTunes的音乐读成服务器可以识别的songData 。
当选完音乐后记得要执行dismiss操作哦
-(void)mediaPickerDidCancel:(MPMediaPickerController *)mediaPicker{
[mediaPicker dismissViewController Animated:YES completion:nil];
}
网友评论