我用谷歌搜索了这个问题,但没有找到任何解决方案。
所以,我的问题是,
我正在使用 GPUImage
将视频过滤器应用于视频文件。同时,该视频的声音没有播放。我知道在应用过滤器时 GPUImage
不支持声音播放。
那么,我该如何实现呢?
最佳答案
你可以像这样通过添加对AVPlayer
的支持来实现声音播放。
在
GPUImageMovie.h
中,@property(readwrite, nonatomic) BOOL playSound;
在
GPUImageMovie.m
中,像这样更新@interface GPUImageMovie ()
。@interface GPUImageMovie() <AVPlayerItemOutputPullDelegate> { // Add this BOOL hasAudioTrack; ......... ........ // Add all below three lines AVPlayer *theAudioPlayer; CFAbsoluteTime startActualFrameTime; CGFloat currentVideoTime; }
之后,在
-(void)startProcessing
方法中,添加以下行。- (void)startProcessing { // Add this currentVideoTime = 0.0f; ..... ..... // Add this if (self.playSound) { [self setupSound]; } GPUImageMovie __block *blockSelf = self; [inputAsset loadValuesAsynchronouslyForKeys:[NSArray arrayWithObject:@"tracks"] completionHandler: ^{ runSynchronouslyOnVideoProcessingQueue(^{ ......... ......... // Add this startActualFrameTime = CFAbsoluteTimeGetCurrent() - currentVideoTime; ....... ....... }); }]; }
同样,在
-(AVAssetReader*)createAssetReader
中更新它,- (AVAssetReader*)createAssetReader { ....... ....... BOOL shouldRecordAudioTrack = (([audioTracks count] > 0) && (self.audioEncodingTarget != nil)); // Add this hasAudioTrack = ([audioTracks count] > 0); ......... }
在
- (void)processAsset
中,- (void)processAsset { ....... ....... if ([reader startReading] == NO) { NSLog(@"Error reading from file at URL: %@", self.url); return; } // Add this if (self.playSound && hasAudioTrack) { [theAudioPlayer seekToTime:kCMTimeZero]; [theAudioPlayer play]; } ......... ......... }
在
-(void)endProcessing
中,- (void)endProcessing { ......... ......... if (self.playerItem && (displayLink != nil)) { [displayLink invalidate]; // remove from all run loops displayLink = nil; } // Add this if (theAudioPlayer != nil) { [theAudioPlayer pause]; [theAudioPlayer seekToTime:kCMTimeZero]; } ......... ......... }
最后添加新方法
-(void)setupSound
,// Add this - (void)setupSound { if (theAudioPlayer != nil) { [theAudioPlayer pause]; [theAudioPlayer seekToTime:kCMTimeZero]; theAudioPlayer = nil; } theAudioPlayer = [[AVPlayer alloc] initWithURL:self.url]; }
最后,当您创建
GPUImageMovie
对象时,不要忘记将playSound
标志设置为YES。
像这样:
movieFile.playSound = YES;
希望这对您有所帮助。
关于ios - 在 GPUImage 中应用视频过滤器时播放音频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31961915/