Objective c 将选定的音乐文件集成到视频中

Objective c 将选定的音乐文件集成到视频中,objective-c,cocoa-touch,ios,video,mpmusicplayercontroller,Objective C,Cocoa Touch,Ios,Video,Mpmusicplayercontroller,我正在开发一个视频录制应用程序,我希望能够集成用户从iPod库中选择的音乐文件。请分享您对我如何达到这一要求的意见。示例代码非常有用。最终成功地将选定的音乐文件集成到视频中 使用AVAssetExportSession,我们可以使用AVMutableComposition将视频和音频合并在一起 谢谢你们所有人的更新 //此方法合并音频和视频 - (void)mergeAudioAtUrl:(NSURL *)audioUrl withVideoAtUrl:(NSURL *)videoUrl toU

我正在开发一个视频录制应用程序,我希望能够集成用户从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];

 }       
 ];
}
-(void)合并音频自然:(NSURL*)音频URL与视频自然:(NSURL*)视频URL旅游:(NSURL*)输出URL
{
//_imageCaptureCount=[\u imagesArray count]*100;
AVURLAsset*audioAsset=[[AVURLAsset alloc]initWithURL:audioUrl选项:nil];
AVURLAsset*videoAsset=[[AVURLAsset alloc]initWithURL:videoUrl选项:nil];
AVMutableComposition*mixComposition=[AVMutableComposition];
if([[audioAsset tracksWithMediaType:AVMediaTypeAudio]计数])
{
AVMutableCompositionTrack*compositionCommentaryTrack=[mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio
preferredTrackID:kCompersistentTrackID_无效];
[compositionCommentaryTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero,videoAsset.duration)
ofTrack:[[audioAsset tracksWithMediaType:AVMediaTypeAudio]对象索引:0]
时间:kCMTimeZero错误:nil];
}
AVMutableCompositionTrack*compositionVideoTrack=[mixComposition addMutableTrackWithMediaType:AVMediaTypeVideo
preferredTrackID:kCompersistentTrackID_无效];
[compositionVideoTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero,videoAsset.duration)
ofTrack:[[videoAsset tracksWithMediaType:AVMediaTypeVideo]对象索引:0]
时间:kCMTimeZero错误:nil];
[音频资产释放];
[视频资产释放];
AVAssetExportSession*\u assetExport=[[AVAssetExportSession alloc]initWithAsset:mixComposition
预设名称:AVAssetExportPresetPassthrough];
NSURL*exportUrl=[NSURL fileURLWithPath:[NSString stringWithFormat:@“%@/Documents/%@Video.mp4”,NSHomeDirectory(),pcNameString]];
如果([[NSFileManager defaultManager]文件ExistSatPath:[NSString stringWithFormat:@“%@/Documents/%@Video.mp4”,NSHomeDirectory(),pcNameString]]))
{
[[NSFileManager defaultManager]removeItemAtPath:[NSString stringWithFormat:@“%@/Documents/%@Video.mp4”,NSHomeDirectory(),pcNameString]错误:nil];
}
_assetExport.outputFileType=@“com.apple.quicktime电影”;//com.apple.m4v-video
_assetExport.outputURL=exportUrl;
_assetExport.shouldOptimizationForNetworkUse=是;
[\u assetExport exportAsynchronouslyWithCompletionHandler:
^(无效){
//你的完成代码在这里
//NSLog(@“已完成”);
removeProgresBarFlag=是;
/*NSString*savedVideoFilePath=[NSString stringWithFormat:@“%@/Documents/PC%d.mp4”,NSHomeDirectory(),[videosListArray计数];
if(UIVideoAtPath与SavedPhotosAlbum(savedVideoFilePath)兼容)
{
[[UIApplication sharedApplication]beginIgnoringInteractionEvents];
UISaveVideoAtPathToSavedPhotosAlbum(savedVideoFilePath,self,nil,nil);
[[UIApplication sharedApplication]endIgnoringInteractionEvents];
} */
NSMutableDictionary*videoDetailDict=[[NSMutableDictionary alloc]initWithCapacity:0];
NSSTRING编码;
n错误*错误;
NSString*persistentID;
NSFileManager*fileManager=[NSFileManager defaultManager];
if([fileManager fileExistsAtPath:PRESENTSONGS\u FILE\u PATH])
persistentID=[NSString stringWithContentsOfFile:PRESENTSONGS\u FILE\u使用的路径编码:&编码错误:&错误];
其他的
persistentID=@”;
[videoDetailDict setObject:persistentID forKey:KSong];
如果([fileManager文件ExistSatPath:PRESENTIMAGES\u文件])
{
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发布];
[videoDetailDict setObject:currentImagesArray forKey:KImagesList];
if([fileManager fileExistsAtPath:TEMPVIDEO\u FILE\u PATH])
[fileManager removeItemAtPath:TEMPVIDEO_文件_路径错误:nil];
NSString*主路径;
mainPath=[NSString stringWithFormat:@“%@/Documents/%@文件”,NSHomeDirectory(),pcNameString];
如果([fileManager fileExistsAtPath:mainPath])
[fileManager removeItemAtPath:mainPath错误:无];
[fileManager createDirectoryAtPath:mainPath with IntermediateDirectory:无属性:nil错误:nil];

对于(int i=0;iHi,你能帮我吗?我正在处理同一个用例,但无法在合并文件中获取视频。我能够获取AVAssetExportSessionStatusCompleted状态,但无法查看视频。我已检查了我的视频文件,它是正确的。我的音频文件也是正确的…但在合并两个视频时,不会显示视频。…你能告诉我有什么问题吗?更新我的答案,检查一下!