美攝SDK的使用(四)—— 短視頻的編輯工具類的封裝

版本記錄

版本號 時間
V1.0 2017.08.17

前言

針對短視頻的上傳、編輯等功能有很多的SDK税手,比如騰訊的SDK、七牛的SDK等需纳,這里我就說一下我用過的美攝的SDK - 1.8.0芦倒,希望對大家有所幫助。感興趣的可以看我上面幾篇不翩。
1. 美攝SDK的使用(一)—— 產(chǎn)品介紹
2. 美攝SDK的使用(二)—— 框架介紹
3. 美攝SDK的使用(三)—— 短視頻的錄制工具類的封裝

短視頻編輯工具類的封裝

下面我就封裝了一下短視頻編輯的工具兵扬。

1. JJShortVideoEditManager.h

@class NvsStreamingContext;
@class NvsLiveWindow;
@class NvsTimeline;
@class JJEditVideoModel;

@protocol JJShortVideoEditDelegate <NSObject>

- (void)beginLoadShortVideo:(NSString *)path;

- (void)loadLoaderProcess:(NSInteger)process;

- (void)shortVideoUploadFaile;

- (void)saveToLibrary;

- (void)didPlaybackEOF:(NvsTimeline *)timeline;

- (void)didPlaySuccess;

@end

@interface JJShortVideoEditManager : NSObject

@property (nonatomic, weak) id<JJShortVideoEditDelegate>delegate;
@property (nonatomic, assign) int type;

- (void)loadPreView:(NvsLiveWindow *)preview;

//取得默認封面
- (UIImage *)selectDefaletCoverImage;

//加載短視頻
- (void)loadVideoPath:(NSMutableArray <JJEditVideoModel *>*)videoArray;

- (NvsStreamingContext *)context;

- (NvsTimeline *)timeLine;

- (void)loadPlay;

- (void)saveShortVideo:(NSString *)path;

- (NSArray *)loadStickerArray;

- (NSArray *)loadFxArray;

- (void)addStickerForShortVideo:(NSInteger)index;

- (void)addFxForShortVideo:(NSInteger)index;

- (void)clearCache;

- (void)stopPlay;

@end
2.JJShortVideoEditManager.m
#import "JJShortVideoEditManager.h"
#import "NvsStreamingContext.h"
#import "NvsVideoTrack.h"
#import "NvsTimeline.h"
#import "JJEditVideoModel.h"
#import "NvsVideoClip.h"
#import "NvsFxDescription.h"

@interface JJShortVideoEditManager () <NvsStreamingContextDelegate>

@property (nonatomic, strong) NvsStreamingContext *context;
@property (nonatomic, strong) NvsTimeline *timeLine;
@property (nonatomic, strong) NvsVideoTrack *videoTrack;
@property (nonatomic, strong) NvsLiveWindow *preView;
@property (nonatomic, strong) NSArray <JJEditVideoModel *>*videoArray;
@property (nonatomic, copy) NSString *path;
@property (nonatomic, copy) NSMutableString *stickerPackageId;
@property (nonatomic, copy) NSMutableString *videoFxPackageId;
@property (nonatomic, strong) NSArray *lstVideoFx;
@property (nonatomic, strong) NSArray *lstVideoTransition;
@property (nonatomic, assign) BOOL isSave;
@property (nonatomic, assign) BOOL hasAddedSticker;

@end

@implementation JJShortVideoEditManager

#pragma mark - Override Base Function

- (void)dealloc
{
    DDLogWarn(@"%@ 已釋放", self);
}

#pragma mark - Object Public Function

//加載預覽視圖
- (void)loadPreView:(NvsLiveWindow *)preview
{
    _preView = preview;
}

//加載短視頻
- (void)loadVideoPath:(NSArray <JJEditVideoModel *>*)videoArray
{
    _videoArray = videoArray;
}

//時間線

- (NvsTimeline *)timeLine
{
    if (!_timeLine) {
        if (!_timeLine) {
            NvsVideoResolution videoEditRes;
            videoEditRes.imageWidth = 720/2;
            videoEditRes.imageHeight = 1280/2;
            videoEditRes.imagePAR = (NvsRational){1, 1};
            NvsRational videoFps = {25, 1};
            NvsAudioResolution audioEditRes;
            audioEditRes.sampleRate = 48000;
            audioEditRes.channelCount = 2;
            audioEditRes.sampleFormat = NvsAudSmpFmt_S16;
            NvsTimeline *timeLine = [self.context createTimeline:&videoEditRes videoFps:&videoFps audioEditRes:&audioEditRes];
            _timeLine = timeLine;
            _videoTrack = [timeLine appendVideoTrack];
            for (JJEditVideoModel *model in self.videoArray) {
                [_videoTrack appendClip:model.path];
            }
        }
        if (!self.context.delegate) {
            self.context.delegate = self;
        }
        [self.context connectTimeline:_timeLine withLiveWindow:self.preView];
    }
    if (!self.context.delegate) {
        self.context.delegate = self;
        [self.context connectTimeline:self.timeLine withLiveWindow:self.preView];
    }
    return _timeLine;
}

//播放

- (void)loadPlay
{
    self.context.delegate = self;
    [self.context connectTimeline:self.timeLine withLiveWindow:self.preView];
    if ([self.context playbackTimeline:self.timeLine startTime:0 endTime:self.timeLine.duration videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize preload:YES flags:0]) {
        NSLog(@"播放成功");
    }
//    [self.context playbackTimeline:self.timeLine startTime:0 endTime:self.timeLine.duration videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize preload:YES flags:0];
}

- (void)saveShortVideo:(NSString *)path
{
    if (self.context.delegate == nil) {
        self.context.delegate = self;
    }
     _path = path;
    NvsCompileVideoResolutionGrade grade;
    if (ZebraUIDevice_iphone5 || ZebraUIDevice_iphone4 || ZebraUIDevice_iphone4S) {
        grade = NvsCompileVideoResolutionGrade480;
    }
    else if (ZebraUIDevice_iphone5S || ZebraUIDevice_iphone5C){
        grade = NvsCompileVideoResolutionGrade720;
    }
    else {
        grade = NvsCompileVideoResolutionGrade1080;
    }
    
    if ([self.context compileTimeline:self.timeLine startTime:0 endTime:self.timeLine.duration outputFilePath:path videoResolutionGrade:grade videoBitrateGrade:NvsCompileBitrateGradeHigh flags:0]) {
    }
    else {
        NSLog(@"上傳失敗,請重試");
        if (_type == 1) {
            if ([self.delegate respondsToSelector:@selector(shortVideoUploadFaile)]) {
                [self.delegate shortVideoUploadFaile];
            }
        }        
    }
}

//貼紙
- (void)addStickerForShortVideo:(NSInteger)index
{
    if (_hasAddedSticker) {
        NvsTimelineAnimatedSticker *sticker = [self.timeLine getFirstAnimatedSticker];
        while (sticker)
            sticker = [self.timeLine removeAnimatedSticker:sticker];
        _hasAddedSticker = NO;
        
    }
    else {
        if ([_stickerPackageId isEqualToString:@""])
            return;
        
        for (unsigned int i = 0; i < _videoTrack.clipCount; i++) {
            NvsVideoClip *videoClip = [_videoTrack getClipWithIndex:i];
            [videoClip setPan:0 andScan:1];
            [self.timeLine addAnimatedSticker:videoClip.inPoint duration:videoClip.outPoint - videoClip.inPoint animatedStickerPackageId:_stickerPackageId];
        }
        _hasAddedSticker = YES;
    }
    [self loadPlay];
}

- (void)addFxForShortVideo:(NSInteger)index
{
    if (_videoTrack.clipCount <= 0)
        return;
    if (index > 0) {
        NSString *fxName = [_lstVideoFx objectAtIndex:index];
        if ([fxName isEqualToString:@"Beauty"]) {
            
            NvsFxDescription *fxDescription = [_context getVideoFxDescription:fxName];
            NSArray *paramsInfo = [fxDescription getAllParamsInfo];
            for (unsigned int i = 0; i < _videoTrack.clipCount; i++) {
                NvsVideoClip *videoClip = [_videoTrack getClipWithIndex:i];
                [videoClip removeAllFx];
                [videoClip appendBeautyFx];
            }
        }
        else {
            
            if ([fxName isEqualToString:@"None"]) {
                for (unsigned int i = 0; i < _videoTrack.clipCount; i++)
                    [[_videoTrack getClipWithIndex:i] removeAllFx];
            } else if ([fxName isEqualToString:@"Package1"]) {
                for (unsigned int i = 0; i < _videoTrack.clipCount; i++) {
                    NvsVideoClip *videoClip = [_videoTrack getClipWithIndex:i];
                    [videoClip removeAllFx];
                    [videoClip appendPackagedFx:_videoFxPackageId];
                }
            } else {
                for (unsigned int i = 0; i < _videoTrack.clipCount; i++) {
                    NvsVideoClip *videoClip = [_videoTrack getClipWithIndex:i];
                    [videoClip removeAllFx];
                    [videoClip appendBuiltinFx:fxName];
                }
            }
        }
    }
    else {
        NSString *transName = [_lstVideoTransition objectAtIndex:index];
        if ([transName isEqualToString:@"None"])
            transName = @"";
        for (unsigned int i = 0; i < _videoTrack.clipCount - 1; i++)
            [_videoTrack setBuiltinTransition:i withName:transName];
    }
    
    [self loadPlay];
}

- (void)stopPlay
{
    [self.context stop];
}

- (void)clearCache
{
    [self.context stop];
    [self.context clearCachedResources:YES];
    self.context.delegate = nil;
}

- (UIImage *)selectDefaletCoverImage
{
    int64_t timeInterval = 1000*500;
    UIImage *image = [self.context grabImageFromTimeline:self.timeLine timestamp:timeInterval proxyScale:nil];
    return image;
}

- (NSArray *)loadStickerArray
{
    _stickerPackageId = [[NSMutableString alloc] initWithString:@""];
    NSString *sitckerFilePath = [[[NSBundle mainBundle]bundlePath ]stringByAppendingPathComponent:@"89740AEA-80D6-432A-B6DE-E7F6539C4121.animatedsticker"];
    if (![[NSFileManager defaultManager] fileExistsAtPath:sitckerFilePath]) {
        DDLogError(@"Sticker package file is not exist!");
    } else {
        NvsAssetPackageManagerError error = [self.context.assetPackageManager installAssetPackage:sitckerFilePath license:nil type:NvsAssetPackageType_AnimatedSticker sync:YES assetPackageId:_stickerPackageId];
        if (error != NvsAssetPackageManagerError_NoError && error != NvsAssetPackageManagerError_AlreadyInstalled) {
            DDLogError(@"Failed to install sticker package!");
        }
    }
    return @[@"貼紙"];
}

- (NSArray *)loadFxArray
{
    _videoFxPackageId = [[NSMutableString alloc] initWithString:@""];
    bool package1Valid = true;
    NSString *appPath =[[NSBundle mainBundle] bundlePath];
    NSString *package1Path = [appPath stringByAppendingPathComponent:@"7FFCF99A-5336-4464-BACD-9D32D5D2DC5E.videofx"];
    if (![[NSFileManager defaultManager] fileExistsAtPath:package1Path]) {
        DDLogError(@"Video fx package file is not exist!");
        package1Valid = false;
    } else {
        NvsAssetPackageManagerError error = [_context.assetPackageManager installAssetPackage:package1Path license:nil type:NvsAssetPackageType_VideoFx sync:YES assetPackageId:_videoFxPackageId];
        if (error != NvsAssetPackageManagerError_NoError && error != NvsAssetPackageManagerError_AlreadyInstalled) {
            DDLogError(@"Failed to install video fx package!");
            package1Valid = false;
        }
    }
    
    NSMutableArray *lstVideoFx = [NSMutableArray arrayWithObject:@"None"];
    [lstVideoFx addObject:@"Beauty"];
    [lstVideoFx addObjectsFromArray:[_context getAllBuiltinVideoFxNames]];
    if (package1Valid)
        [lstVideoFx addObject:@"Package1"];
    _lstVideoFx = lstVideoFx.copy;
    NSMutableArray *lstVideoTransition = [NSMutableArray arrayWithObject:@"None"];
    [lstVideoTransition addObjectsFromArray:[self.context getAllBuiltinVideoTransitionNames]];
    _lstVideoTransition = lstVideoFx.copy;
    return _lstVideoFx.copy;
}

#pragma mark - Object Private Function

- (void)beginLoadShortVideo:(NSString *)path
{
    if ([self.delegate respondsToSelector:@selector(beginLoadShortVideo:)]) {
        [self.delegate beginLoadShortVideo:path];
    }
}

- (void)saveToLibrary
{
    if ([self.delegate respondsToSelector:@selector(saveToLibrary)]) {
        [self.delegate saveToLibrary];
    }
}

- (void)loadLoaderProcess:(NSInteger)process
{
    if ([self.delegate respondsToSelector:@selector(loadLoaderProcess:)]) {
        [self.delegate loadLoaderProcess:process];
    }
}

//監(jiān)聽

- (void)didPlaybackEOF:(NvsTimeline *)timeline
{
    if ([self.delegate respondsToSelector:@selector(didPlaybackEOF:)]) {
        [self.delegate didPlaybackEOF:timeline];
    }
}

#pragma mark - Lazy Load

- (NvsStreamingContext *)context
{
    if (!_context) {
        _context = [NvsStreamingContext sharedInstance];
        _context.delegate = self;
    }
    return _context;
}

#pragma mark - NvsStreamingContextDelegate

- (void)didPlaybackStopped:(NvsTimeline *)timeline
{
    if ([self.delegate respondsToSelector:@selector(didPlaybackEOF:)]) {
        [self.delegate didPlaybackEOF:timeline];
    }
}

- (void)didStreamingEngineStateChanged:(NvsStreamingEngineState)state
{
    if (state == NvsStreamingEngineState_CapturePreview) {
        if ([self.delegate respondsToSelector:@selector(didPlaybackEOF:)]) {
            [self.delegate didPlaybackEOF:_timeLine];
        }
    }
}

- (void)didFirstVideoFramePresented:(NvsTimeline *)timeline
{
    if ([self.delegate respondsToSelector:@selector(didPlaySuccess)]) {
        [self.delegate didPlaySuccess];
    }
}

- (void)didCompileProgress:(NvsTimeline *)timeline progress:(int)progress
{
    NSLog(@"process  :   %d", progress);
    if (_type == 1) {
        [self loadLoaderProcess:progress/2];
    }
}

- (void)didCompileFailed:(NvsTimeline *)timeline
{
    NSLog(@"生成失敗");
    if ([self.delegate respondsToSelector:@selector(shortVideoUploadFaile)]) {
        [self.delegate shortVideoUploadFaile];
    }
}

- (void)didCompileFinished:(NvsTimeline *)timeline
{
    NSLog(@"生成成功");
    if (_type == 1) {
        [self beginLoadShortVideo:_path];
    }
    else {
        if (_isSave) {
            return;
        }
        if ([self.delegate respondsToSelector:@selector(saveToLibrary)]) {
            _isSave = YES;
            [self.delegate saveToLibrary];
        }
    }
}

@end

這個工具可以實現(xiàn)對短視頻進行特效編輯口蝠、背景音樂加載等功能器钟。

后記

未完,待續(xù)~~~

金色的路
最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末妙蔗,一起剝皮案震驚了整個濱河市傲霸,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌眉反,老刑警劉巖昙啄,帶你破解...
    沈念sama閱讀 206,602評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異寸五,居然都是意外死亡梳凛,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,442評論 2 382
  • 文/潘曉璐 我一進店門梳杏,熙熙樓的掌柜王于貴愁眉苦臉地迎上來韧拒,“玉大人,你說我怎么就攤上這事十性∨岩纾” “怎么了?”我有些...
    開封第一講書人閱讀 152,878評論 0 344
  • 文/不壞的土叔 我叫張陵劲适,是天一觀的道長楷掉。 經(jīng)常有香客問我,道長减响,這世上最難降的妖魔是什么靖诗? 我笑而不...
    開封第一講書人閱讀 55,306評論 1 279
  • 正文 為了忘掉前任,我火速辦了婚禮支示,結果婚禮上刊橘,老公的妹妹穿的比我還像新娘。我一直安慰自己颂鸿,他們只是感情好促绵,可當我...
    茶點故事閱讀 64,330評論 5 373
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般败晴。 火紅的嫁衣襯著肌膚如雪浓冒。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,071評論 1 285
  • 那天尖坤,我揣著相機與錄音稳懒,去河邊找鬼。 笑死慢味,一個胖子當著我的面吹牛场梆,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播纯路,決...
    沈念sama閱讀 38,382評論 3 400
  • 文/蒼蘭香墨 我猛地睜開眼或油,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了驰唬?” 一聲冷哼從身側響起顶岸,我...
    開封第一講書人閱讀 37,006評論 0 259
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎叫编,沒想到半個月后辖佣,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 43,512評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡宵溅,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 35,965評論 2 325
  • 正文 我和宋清朗相戀三年凌简,在試婚紗的時候發(fā)現(xiàn)自己被綠了上炎。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片恃逻。...
    茶點故事閱讀 38,094評論 1 333
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖藕施,靈堂內(nèi)的尸體忽然破棺而出寇损,到底是詐尸還是另有隱情,我是刑警寧澤裳食,帶...
    沈念sama閱讀 33,732評論 4 323
  • 正文 年R本政府宣布矛市,位于F島的核電站,受9級特大地震影響诲祸,放射性物質發(fā)生泄漏浊吏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 39,283評論 3 307
  • 文/蒙蒙 一救氯、第九天 我趴在偏房一處隱蔽的房頂上張望找田。 院中可真熱鬧,春花似錦着憨、人聲如沸墩衙。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,286評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽漆改。三九已至心铃,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間挫剑,已是汗流浹背去扣。 一陣腳步聲響...
    開封第一講書人閱讀 31,512評論 1 262
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留樊破,地道東北人厅篓。 一個月前我還...
    沈念sama閱讀 45,536評論 2 354
  • 正文 我出身青樓,卻偏偏與公主長得像捶码,于是被迫代替她去往敵國和親羽氮。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 42,828評論 2 345

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