objective-c - 将选定的音乐文件整合到视频中

标签 objective-c cocoa-touch ios video mpmusicplayercontroller

我正在开发一个视频录制应用程序,我希望能够集成用户从 iPod 库中选择的音乐文件。请分享您关于如何实现此要求的意见。示例代码很有帮助。

最佳答案

终于成功将选定的音乐文件整合到视频中

使用 AVAssetExportSession,我们可以使用 AVMutableComposition 将视频和音频合并在一起。

感谢大家的更新!!

//该方法合并了音频和视频。

- (void)mergeAudioAtUrl:(NSURL *)audioUrl withVideoAtUrl:(NSURL *)videoUrl toUrl:(NSURL *)outputUrl
  {

//_imageCaptureCount = [_imagesArray count]*100;

AVURLAsset* audioAsset = [[AVURLAsset alloc]initWithURL:audioUrl options:nil];
AVURLAsset* videoAsset = [[AVURLAsset alloc]initWithURL:videoUrl options:nil];

AVMutableComposition* mixComposition = [AVMutableComposition composition];


if([[audioAsset tracksWithMediaType:AVMediaTypeAudio] count])
{
    AVMutableCompositionTrack *compositionCommentaryTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio 
                                                                                        preferredTrackID:kCMPersistentTrackID_Invalid];

    [compositionCommentaryTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, videoAsset.duration) 
                                        ofTrack:[[audioAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0] 
                                         atTime:kCMTimeZero error:nil];
}
AVMutableCompositionTrack *compositionVideoTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeVideo 
                                                                               preferredTrackID:kCMPersistentTrackID_Invalid];
[compositionVideoTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, videoAsset.duration) 
                               ofTrack:[[videoAsset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0] 
                                atTime:kCMTimeZero error:nil];

[audioAsset release];
[videoAsset release];

AVAssetExportSession* _assetExport = [[AVAssetExportSession alloc] initWithAsset:mixComposition 
                                                                      presetName:AVAssetExportPresetPassthrough];   

NSURL    *exportUrl = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/Documents/%@Video.mp4", NSHomeDirectory(),pcNameString]];

if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/Documents/%@Video.mp4", NSHomeDirectory(),pcNameString]]) 
{
    [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/Documents/%@Video.mp4", NSHomeDirectory(),pcNameString] error:nil];
}

_assetExport.outputFileType = @"com.apple.quicktime-movie"; //com.apple.m4v-video
_assetExport.outputURL = exportUrl;
_assetExport.shouldOptimizeForNetworkUse = YES;

[_assetExport exportAsynchronouslyWithCompletionHandler:
 ^(void ) {      
     // your completion code here
    // NSLog(@"completed");

     removeProgresBarFlag = YES;


    /* NSString* savedVideoFilePath = [NSString stringWithFormat:@"%@/Documents/PC%d.mp4", NSHomeDirectory(),[videosListArray count]];

     if(UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(savedVideoFilePath))
     {
         [[UIApplication sharedApplication]beginIgnoringInteractionEvents];
         UISaveVideoAtPathToSavedPhotosAlbum(savedVideoFilePath, self, nil, nil);
         [[UIApplication sharedApplication]endIgnoringInteractionEvents];

     } */


     NSMutableDictionary* videoDetailDict = [[NSMutableDictionary alloc] initWithCapacity:0];

     NSStringEncoding encoding;
     NSError* error;

     NSString * persistentID;
     NSFileManager* fileManager = [NSFileManager defaultManager];

     if([fileManager fileExistsAtPath:PRESENTSONGS_FILE_PATH])
         persistentID = [NSString stringWithContentsOfFile:PRESENTSONGS_FILE_PATH usedEncoding:&encoding error:&error];
     else 
         persistentID = @"";

     [videoDetailDict setObject:persistentID forKey:KSong];

     if([fileManager fileExistsAtPath:PRESENTIMAGES_FILE])
     {

         NSMutableArray* currentImagesArray = [[NSMutableArray alloc] initWithContentsOfFile:IMAGESDATA_FILE_PATH];
         NSMutableArray* durationArray = [[NSMutableArray alloc] initWithContentsOfFile:[NSString stringWithFormat:@"%@/videoduration.plist", [[NSBundle mainBundle] resourcePath]]];
         [videoDetailDict setObject:[durationArray objectAtIndex:[currentImagesArray count]-1] forKey:KfileSize];
         [durationArray release];


         [videoDetailDict setObject:currentImagesArray forKey:KImagesList];
         if([fileManager fileExistsAtPath:TEMPVIDEO_FILE_PATH])
         [fileManager removeItemAtPath:TEMPVIDEO_FILE_PATH error:nil];

         NSString* mainPath;

             mainPath = [NSString stringWithFormat:@"%@/Documents/%@File",NSHomeDirectory(),pcNameString];

         if([fileManager fileExistsAtPath:mainPath])
             [fileManager removeItemAtPath:mainPath error:nil];

         [fileManager createDirectoryAtPath:mainPath withIntermediateDirectories:NO attributes:nil error:nil];


         for(int i=0;i<[currentImagesArray count];i++)
         {
             [fileManager copyItemAtPath:[NSString stringWithFormat:@"%@%@",PRESENTIMAGES_FILE,[currentImagesArray objectAtIndex:i]] toPath:[NSString stringWithFormat:@"%@/%@",mainPath,[currentImagesArray objectAtIndex:i]] error:nil];
         }
         [currentImagesArray release];

     }

     if([fileManager fileExistsAtPath:KMESSAGE_FILEPATH])
     {
         NSMutableDictionary* currentMessageDictioanry = [[NSMutableDictionary alloc] initWithContentsOfFile:KMESSAGE_FILEPATH];
         [videoDetailDict setObject:currentMessageDictioanry forKey:Kmessage];
         [currentMessageDictioanry release];
     }

     [videoDetailDict setObject:pcNameString forKey:KPostCardName]; //[NSString stringWithFormat:@"PostCard Video%d",[videosListArray count]]
     //[videosListArray insertObject:videoDetailDict atIndex:0];
     [videosListArray addObject:videoDetailDict];
     [videoDetailDict release];
     [videosListArray writeToFile:VIDEOS_FILE_PATH atomically:YES];

 }       
 ];
}

关于objective-c - 将选定的音乐文件整合到视频中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6106172/

相关文章:

ios - 什么时候为 NSDateFormatter 设置 NSLocale ?

iOS Framework Delegate 和 IBAction 没有在 Swift 中被调用

iphone - Objective C 颜色编码?

objective-c - 编译 pod 时出现 “Include of non-modular header inside framework module”

ios - 苹果ios的后台执行示例

ios - 形状图层的动画路径

ios - 跨 View Controller 发送 UITableViewCell

ios - SocketScan 在 Swift 中获取电池电量

ios - 如何在我的 ios 应用程序中为帮助页面添加此格式化文本

objective-c - 拆除 UIViewController 时是否总是调用 viewDidUnload 和 dealloc?