使用AVAssetReader播放声音

时间:2011-09-27 02:14:07

标签: iphone ios avfoundation

我正在使用AVAssetReader从视频文件中获取各个帧(请参阅下面的代码)。我想知道如何同时播放视频中的音频。

我尝试将音频分成新文件并使用AVAudioPlayer播放,但如果我在AVAssetReader的同时使用它,则会崩溃。

NSAutoreleasePool *pool = [NSAutoreleasePool new];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];    
NSString* fullPath = [[documentsDirectory stringByAppendingPathComponent:@"sample_video.mp4"] retain];
NSString *urlAddress = fullPath;
NSURL *url = [NSURL fileURLWithPath:urlAddress];
AVURLAsset *urlAsset = [[AVURLAsset alloc] initWithURL:url options:nil];
NSArray *tracks = [urlAsset tracksWithMediaType:AVMediaTypeVideo];
AVAssetTrack *track = [tracks objectAtIndex:0];
NSDictionary* trackDictionary = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:kCVPixelFormatType_32BGRA] 
                                                            forKey:(id)kCVPixelBufferPixelFormatTypeKey];

AVAssetReaderTrackOutput *asset_reader_output = [[AVAssetReaderTrackOutput alloc] initWithTrack:track outputSettings:trackDictionary];

AVAssetReader *asset_reader = [[AVAssetReader alloc] initWithAsset:urlAsset error:nil];
[asset_reader addOutput:asset_reader_output];
[asset_reader startReading];

while (asset_reader.status == AVAssetReaderStatusReading){

    CMSampleBufferRef sampleBufferRef = [asset_reader_output copyNextSampleBuffer];

    if (sampleBufferRef){
            [self performSelectorOnMainThread:@selector(processFrame) withObject:nil waitUntilDone:YES];
    }
    CMSampleBufferInvalidate(sampleBufferRef);
    CFRelease(sampleBufferRef);
}
[pool release];

0 个答案:

没有答案