我可以从MPMusicPlayerController获取音频会话/应用音频单元吗?

时间:2010-05-03 18:23:50

标签: iphone audio avaudioplayer ipod mpmusicplayercontroller

我想控制来自MPMusicPlayerController的音频(即从iPod库播放)。例如,我想将EQ应用于它,或者做DSP,混响等等。

这可能吗?有没有我可以抓住的音频会话?或者,是否有某种方法可以使用AVAudioPlayer播放iPod库中的文件?

1 个答案:

答案 0 :(得分:6)

MPMusicPLayerController无法与AV Framework“很好地”工作 我设法得到一些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 );