iOS 視頻拼接以及添加背景音樂

- (void)joinVideoAndMusic {
    NSURL *videoURL1 = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"IMG_4400" ofType:@"m4v"]];
    NSURL *videoURL2 = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"IMG_5170" ofType:@"mp4"]];
    NSURL *musicURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"littlelucky" ofType:@"mp3"]];
    AVAsset *asset1 = [AVAsset assetWithURL:videoURL1];
    AVAsset *asset2 = [AVAsset assetWithURL:videoURL2];
    AVAsset *asset3 = [AVAsset assetWithURL:musicURL];
    
    AVMutableComposition *mixComposition = [[AVMutableComposition alloc] init];
    AVMutableCompositionTrack *videoTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
    [videoTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, asset1.duration) ofTrack:[asset1 tracksWithMediaType:AVMediaTypeVideo].firstObject atTime:kCMTimeZero error:nil];
    [videoTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, asset2.duration) ofTrack:[asset2 tracksWithMediaType:AVMediaTypeVideo].firstObject atTime:asset1.duration error:nil];
    if (asset3 != nil) {
        AVMutableCompositionTrack *audioTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
        [audioTrack insertTimeRange:CMTimeRangeMake(CMTimeAdd(asset1.duration, asset2.duration), CMTimeAdd(asset1.duration, asset2.duration)) ofTrack:[asset3 tracksWithMediaType:AVMediaTypeAudio].firstObject atTime:kCMTimeZero error:nil];
        
        _audioMix = [AVMutableAudioMix audioMix];
        if (asset3) {
            AVMutableAudioMixInputParameters *audioParam = [AVMutableAudioMixInputParameters audioMixInputParametersWithTrack:audioTrack];
            [audioParam setVolumeRampFromStartVolume:0 toEndVolume:1 timeRange:CMTimeRangeMake(kCMTimeZero,asset1.duration)];
            [audioParam setVolumeRampFromStartVolume:1 toEndVolume:0 timeRange:CMTimeRangeMake(asset1.duration, asset2.duration)];
            [audioParam setTrackID:audioTrack.trackID];
            _audioMix.inputParameters = @[audioParam];
        }
    }
    
    NSString *outputPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/CustomMovie.mp4"];
    unlink([outputPath UTF8String]);   // 刪除當(dāng)前該路徑下的文件
    NSURL *outputURL = [NSURL fileURLWithPath:outputPath];
    
    
    _exporter = [[AVAssetExportSession alloc] initWithAsset:mixComposition presetName:AVAssetExportPresetHighestQuality];
    _exporter.outputURL = outputURL;
    _exporter.outputFileType = AVFileTypeQuickTimeMovie;
    _exporter.shouldOptimizeForNetworkUse = YES;
    _exporter.audioMix = _audioMix;
    __weak typeof(self) weakSelf = self;
    [_exporter exportAsynchronouslyWithCompletionHandler:^{
        // 視頻輸出完成
        switch (weakSelf.exporter.status) {
            case AVAssetExportSessionStatusCompleted:
                [weakSelf saveVideoToLibrary:outputPath];
                break;
            case AVAssetExportSessionStatusFailed:
                kShowPopTip(nil, @"導(dǎo)出失敗", nil);
                break;
            case AVAssetExportSessionStatusCancelled:
                kShowPopTip(nil, @"導(dǎo)出取消", nil);
                break;
            default:
                break;
        }
    }];
}
- (void)saveVideoToLibrary:(NSString *)outputPath {
    if ([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusAuthorized) {
        
        __block PHObjectPlaceholder *placeholder;
        if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(outputPath)) {
            NSError *error;
            [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
                PHAssetChangeRequest* createAssetRequest = [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:[NSURL URLWithString:outputPath]];
                placeholder = [createAssetRequest placeholderForCreatedAsset];
            } error:&error];
            if (error) {
                kShowPopTip(self.view, error.description, nil);
            }else {
                kShowPopTip(self.view, @"視頻已保存到相冊", nil);
            }
        }
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌蕊梧,老刑警劉巖隘膘,帶你破解...
    沈念sama閱讀 222,729評論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件睬罗,死亡現(xiàn)場離奇詭異诗赌,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)盔沫,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,226評論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來枫匾,“玉大人架诞,你說我怎么就攤上這事「绍裕” “怎么了谴忧?”我有些...
    開封第一講書人閱讀 169,461評論 0 362
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我沾谓,道長委造,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 60,135評論 1 300
  • 正文 為了忘掉前任均驶,我火速辦了婚禮昏兆,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘妇穴。我一直安慰自己爬虱,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 69,130評論 6 398
  • 文/花漫 我一把揭開白布腾它。 她就那樣靜靜地躺著跑筝,像睡著了一般。 火紅的嫁衣襯著肌膚如雪瞒滴。 梳的紋絲不亂的頭發(fā)上曲梗,一...
    開封第一講書人閱讀 52,736評論 1 312
  • 那天,我揣著相機(jī)與錄音逛腿,去河邊找鬼稀并。 笑死,一個胖子當(dāng)著我的面吹牛单默,可吹牛的內(nèi)容都是我干的碘举。 我是一名探鬼主播祷膳,決...
    沈念sama閱讀 41,179評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼控乾,長吁一口氣:“原來是場噩夢啊……” “哼谴蔑!你這毒婦竟也來了惨远?” 一聲冷哼從身側(cè)響起躺枕,我...
    開封第一講書人閱讀 40,124評論 0 277
  • 序言:老撾萬榮一對情侶失蹤剃诅,失蹤者是張志新(化名)和其女友劉穎朝墩,沒想到半個月后侮东,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體粱年,經(jīng)...
    沈念sama閱讀 46,657評論 1 320
  • 正文 獨居荒郊野嶺守林人離奇死亡售滤,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,723評論 3 342
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了台诗。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片完箩。...
    茶點故事閱讀 40,872評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖拉队,靈堂內(nèi)的尸體忽然破棺而出弊知,到底是詐尸還是另有隱情,我是刑警寧澤粱快,帶...
    沈念sama閱讀 36,533評論 5 351
  • 正文 年R本政府宣布秩彤,位于F島的核電站叔扼,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏漫雷。R本人自食惡果不足惜瓜富,卻給世界環(huán)境...
    茶點故事閱讀 42,213評論 3 336
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望珊拼。 院中可真熱鬧食呻,春花似錦、人聲如沸澎现。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,700評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽剑辫。三九已至干旧,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間妹蔽,已是汗流浹背椎眯。 一陣腳步聲響...
    開封第一講書人閱讀 33,819評論 1 274
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留胳岂,地道東北人编整。 一個月前我還...
    沈念sama閱讀 49,304評論 3 379
  • 正文 我出身青樓,卻偏偏與公主長得像乳丰,于是被迫代替她去往敵國和親掌测。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,876評論 2 361

推薦閱讀更多精彩內(nèi)容