2010-08-09 6 views
12

Ich habe eine Videodatei und eine Audiodatei. Ist es möglich, es zu einem Video mit einer Sounddatei zusammenzuführen? Ich denke AVMutableComposition sollte mir helfen, aber ich verstehe immer noch nicht wie. irgendwelche Ratschläge?Wie Audio zu Video-Datei auf iPhone SDK hinzufügen

Antwort

18

Dank Daniel hilft. Ich habe es herausgefunden, es ist einfach. Hier

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

AVMutableComposition* mixComposition = [AVMutableComposition composition]; 

AVMutableCompositionTrack *compositionCommentaryTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio 
                        preferredTrackID:kCMPersistentTrackID_Invalid]; 
[compositionCommentaryTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, audioAsset.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]; 

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

NSString* videoName = @"export.mov"; 

NSString *exportPath = [NSTemporaryDirectory() stringByAppendingPathComponent:videoName]; 
NSURL *exportUrl = [NSURL fileURLWithPath:exportPath]; 

if ([[NSFileManager defaultManager] fileExistsAtPath:exportPath]) 
{ 
    [[NSFileManager defaultManager] removeItemAtPath:exportPath error:nil]; 
} 

_assetExport.outputFileType = @"com.apple.quicktime-movie"; 
DLog(@"file type %@",_assetExport.outputFileType); 
_assetExport.outputURL = exportUrl; 
_assetExport.shouldOptimizeForNetworkUse = YES; 

[_assetExport exportAsynchronouslyWithCompletionHandler: 
^(void) {  
      // your completion code here 
    }  
} 
]; 
+0

actually dieses Stück Code funktioniert nicht richtig..wenn ich diesen Code in mein Projekt implementieren, dann wird abgestürzt sein auf [compositionCementaryTrack insertTimeRange: CMTimeRangeMake (kCMTimeZero, audioAsset.duration) ofTrack: [[audioAsset tracksWithMediaType: AVMediaTypeAudio] objectAtIndex: 0] atTime: kCMTimeZero Fehler: Null]; und zeigt, dass es kein Objekt bei Index Null gibt. – Swastik

+0

@Swastik Ich stoße auf das gleiche Problem bei Gelegenheit, besonders wenn ich mit Dateien von der iCloud arbeite. Die Lösung für mich war, 2 Dinge zu tun. 1) vergewissere dich, dass die Datei, die ich verwenden möchte, für den Medientyp gültig ist, für den ich sie verwende und 2) stelle sicher, dass die Datei tatsächlich Daten enthält (was sie manchmal nicht mit der iCloud tut) – nick

+0

hi Steve, ich füge nur eine einzige Audio-/Videodatei zusammen. Das Problem ist, dass meine Videodatei von 40 Sekunden und Audiodatei von 28 Sekunden ist. Also für die restlichen 12 (40-28) Sekunden - Ich möchte es aus 0 Sekunden in Audiodatei wiederholen. Wie mache ich das? Gibt es einen direkten Weg, dies zu tun? – Hemang

6

Ja, es ist möglich, hier ist ein Code-Schnipsel, das verwendet wird, um Audio zu einer bestehenden Komposition hinzufügen, ich griff dies aus Äpfel Beispielcode, sollten Sie wahrscheinlich das gesamte Projekt anzeigen, Sie finden es sehr nützlich, das Projekt ist AVEditDemo und Sie können es in der WWDC 2010 Material finden, die sie hier veröffentlicht. developer.apple.com/videos/wwdc/2010. Hoffe, dass

- (void)addCommentaryTrackToComposition:(AVMutableComposition *)composition withAudioMix:(AVMutableAudioMix *)audioMix 

{ 

NSInteger i; 

NSArray *tracksToDuck = [composition tracksWithMediaType:AVMediaTypeAudio]; // before we add the commentary 



// Clip commentary duration to composition duration. 

CMTimeRange commentaryTimeRange = CMTimeRangeMake(self.commentaryStartTime, self.commentary.duration); 

if (CMTIME_COMPARE_INLINE(CMTimeRangeGetEnd(commentaryTimeRange), >, [composition duration])) 

    commentaryTimeRange.duration = CMTimeSubtract([composition duration], commentaryTimeRange.start); 



// Add the commentary track. 

AVMutableCompositionTrack *compositionCommentaryTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid]; 

[compositionCommentaryTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, commentaryTimeRange.duration) ofTrack:[[self.commentary tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0] atTime:commentaryTimeRange.start error:nil]; 





NSMutableArray *trackMixArray = [NSMutableArray array]; 

CMTime rampDuration = CMTimeMake(1, 2); // half-second ramps 

for (i = 0; i < [tracksToDuck count]; i++) { 

    AVMutableAudioMixInputParameters *trackMix = [AVMutableAudioMixInputParameters audioMixInputParametersWithTrack:[tracksToDuck objectAtIndex:i]]; 

    [trackMix setVolumeRampFromStartVolume:1.0 toEndVolume:0.2 timeRange:CMTimeRangeMake(CMTimeSubtract(commentaryTimeRange.start, rampDuration), rampDuration)]; 

    [trackMix setVolumeRampFromStartVolume:0.2 toEndVolume:1.0 timeRange:CMTimeRangeMake(CMTimeRangeGetEnd(commentaryTimeRange), rampDuration)]; 

    [trackMixArray addObject:trackMix]; 

} 

audioMix.inputParameters = trackMixArray; 

}

+1

Wo befindet sich diese Demo? Ich kann nirgendwo einen Download finden. –

+0

ja ... wo ist das Demo ??? –

+0

Ich füge nur eine einzelne Audio-/Videodatei zusammen. Das Problem ist, dass meine Videodatei von 40 Sekunden und Audiodatei von 28 Sekunden ist. Also für die restlichen 12 (40-28) Sekunden - Ich möchte es aus 0 Sekunden in Audiodatei wiederholen. Wie mache ich das? Gibt es einen direkten Weg, dies zu tun? – Hemang

0

ist die schnelle Version:

func mixAudio(audioURL audioURL: NSURL, videoURL: NSURL) { 
    let audioAsset = AVURLAsset(URL: audioURL) 
    let videoAsset = AVURLAsset(URL: videoURL) 

    let mixComposition = AVMutableComposition() 

    let compositionCommentaryTrack = mixComposition.addMutableTrackWithMediaType(AVMediaTypeAudio, preferredTrackID: kCMPersistentTrackID_Invalid) 

    // add audio 
    let timeRange = CMTimeRangeMake(kCMTimeZero, audioAsset.duration) 
    let track = audioAsset.tracksWithMediaType(AVMediaTypeAudio)[0] 
    do { 
     try compositionCommentaryTrack.insertTimeRange(timeRange, ofTrack: track, atTime: kCMTimeZero) 
    } 
    catch { 
     print("Error insertTimeRange for audio track \(error)") 
    } 

    // add video 
    let compositionVideoTrack = mixComposition.addMutableTrackWithMediaType(AVMediaTypeVideo, preferredTrackID: kCMPersistentTrackID_Invalid) 

    let timeRangeVideo = CMTimeRangeMake(kCMTimeZero, videoAsset.duration) 
    let trackVideo = videoAsset.tracksWithMediaType(AVMediaTypeVideo)[0] 
    do { 
     try compositionVideoTrack.insertTimeRange(timeRangeVideo, ofTrack: trackVideo, atTime: kCMTimeZero) 
    } 
    catch { 
     print("Error insertTimeRange for video track \(error)") 
    } 

    // export 
    let assetExportSession = AVAssetExportSession(asset: mixComposition, presetName: AVAssetExportPresetPassthrough) 
    let videoName = "export.mov" 
    exportPath = "\(NSTemporaryDirectory())/\(videoName)" 
    let exportURL = NSURL(fileURLWithPath: exportPath!) 

    if NSFileManager.defaultManager().fileExistsAtPath(exportPath!) { 
     do { 
      try NSFileManager.defaultManager().removeItemAtPath(exportPath!) 
     } 
     catch { 
      print("Error deleting export.mov: \(error)") 
     } 
    } 

    assetExportSession?.outputFileType = "com.apple.quicktime-movie" 
    assetExportSession?.outputURL = exportURL 
    assetExportSession?.shouldOptimizeForNetworkUse = true 
    assetExportSession?.exportAsynchronouslyWithCompletionHandler({ 
     print("Mixed audio and video!") 
     dispatch_async(dispatch_get_main_queue(), { 
      print(self.exportPath!) 

     }) 
    }) 

} 
Verwandte Themen