2010-05-03 104 views

回答

6

MPMusicPLayerController不能很好地與AV框架一起工作 我設法得到一些DSP使用MPMusicPlayerController獲取媒體項目,然後獲取該項目的URL。然後使用AVURLAsset 和AVAssetReader。 這樣的事情:

MPMediaItem *currentSong = [myMusicController nowPlayingItem]; 
NSURL *currentSongURL = [currentSong valueForProperty:MPMediaItemPropertyAssetURL]; 
AVURLAsset *songAsset = [AVURLAsset URLAssetWithURL:currentSongURL options:nil]; 
NSError *error = nil;   
AVAssetReader* reader = [[AVAssetReader alloc] initWithAsset:songAsset error:&error]; 

AVAssetTrack* track = [[songAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0]; 

NSMutableDictionary* audioReadSettings = [NSMutableDictionary dictionary]; 
[audioReadSettings setValue:[NSNumber numberWithInt:kAudioFormatLinearPCM] 
        forKey:AVFormatIDKey]; 

AVAssetReaderTrackOutput* readerOutput = [AVAssetReaderTrackOutput assetReaderTrackOutputWithTrack:track outputSettings:audioReadSettings]; 
[reader addOutput:readerOutput]; 
[reader startReading]; 
CMSampleBufferRef sample = [readerOutput copyNextSampleBuffer]; 
while(sample != NULL) 
{ 
    sample = [readerOutput copyNextSampleBuffer]; 

    if(sample == NULL) 
     continue; 

    CMBlockBufferRef buffer = CMSampleBufferGetDataBuffer(sample); 
    CMItemCount numSamplesInBuffer = CMSampleBufferGetNumSamples(sample); 

    AudioBufferList audioBufferList; 

    CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(sample, 
                  NULL, 
                  &audioBufferList, 
                  sizeof(audioBufferList), 
                  NULL, 
                  NULL, 
                  kCMSampleBufferFlag_AudioBufferList_Assure16ByteAlignment, 
                  &buffer 
                  ); 

    for (int bufferCount=0; bufferCount < audioBufferList.mNumberBuffers; bufferCount++) { 
     SInt16* samples = (SInt16 *)audioBufferList.mBuffers[bufferCount].mData; 
     for (int i=0; i < numSamplesInBuffer; i++) { 
      NSLog(@"%i", samples[i]); 
     } 
    } 

    //Release the buffer when done with the samples 
    //(retained by CMSampleBufferGetAudioBufferListWithRetainedblockBuffer) 
    CFRelease(buffer);    

    CFRelease(sample); 
+0

所以使用AVURLAsset你可以直接訪問文件或什麼? – 2011-06-27 17:43:12

+0

是的,您可以完全訪問聲音數據。我將編輯其餘代碼的答案以查看實際數據。 – ugiflezet 2011-06-28 10:33:02

+1

真棒!謝謝 – 2011-07-15 23:21:25