2016-07-23 56 views
0

我最初使用AVFoundation库来修剪视频,但它有一个局限性,即它无法为远程URL执行操作,并且仅适用于本地URL。iOS ffmpeg如何运行一个命令来修剪远程URL视频?

因此,经过进一步的研究,我发现ffmpeg库可以包含在iOS的Xcode项目中。 我已经测试了下面的命令来修整上的命令行远程视频:

ffmpeg -y -ss 00:00:01.000 -i "http://i.imgur.com/gQghRNd.mp4" -t 00:00:02.000 -async 1 cut.mp4 

这将修剪.mp4从1秒到3秒标记。这可以通过我的Mac上的命令行完美工作。

我已经成功编译并将ffmpeg库包含到xcode项目中,但不知道如何继续下一步。

现在我想弄清楚如何在iOS应用程序中使用ffmpeg库来运行此命令。我怎样才能做到这一点?

如果你能指点我一些有用的方向,我会非常感激!如果我可以使用你的解决方案来解决它,我会奖励赏金(2天内,当它给我的选择)。

回答

0

我对此有一些想法。然而,我在iOS上的exp已经非常有限,不确定我的想法是否是最好的方式:

据我所知,通常不可能在iOS上运行cmd工具。也许你必须编写一些链接到ffmpeg库的代码。

这里需要做的所有工作:

  1. 打开输入文件和init一些ffmpeg的背景。
  2. 获取视频流并寻找您想要的时间戳。这可能很复杂。请参阅ffmpeg tutorial获得一些帮助,或查看this以精确查找并处理麻烦的关键帧。
  3. 解码一些帧。直到框架匹配结束时间戳。
  4. 与此同时,将帧编码为一个新的文件作为输出。

ffmpeg源码中的示例非常适合了解如何执行此操作。

一些也许有用代码:

av_register_all(); 
avformat_network_init(); 

AVFormatContext* fmt_ctx; 
avformat_open_input(&fmt_ctx, "http://i.imgur.com/gQghRNd.mp4", NULL, NULL); 

avformat_find_stream_info(fmt_ctx, NULL); 

AVCodec* dec; 
int video_stream_index = av_find_best_stream(fmt_ctx, AVMEDIA_TYPE_VIDEO, -1, -1, &dec, 0); 
AVCodecContext* dec_ctx = avcodec_alloc_context3(NULL); 
avcodec_parameters_to_context(dec_ctx, fmt_ctx->streams[video_stream_index]->codecpar) 
// If there is audio you need, it should be decoded/encoded too. 

avcodec_open2(dec_ctx, dec, NULL); 
// decode initiation done 

av_seek_frame(fmt_ctx, video_stream_index, frame_target, AVSEEK_FLAG_FRAME); 
// or av_seek_frame(fmt_ctx, video_stream_index, timestamp_target, AVSEEK_FLAG_ANY) 
// and for most time, maybe you need AVSEEK_FLAG_BACKWARD, and skipping some following frames too. 

AVPacket packet; 
AVFrame* frame = av_frame_alloc(); 

int got_frame, frame_decoded; 
while (av_read_frame(fmt_ctx, &packet) >= 0 && frame_decoded < second_needed * fps) { 
    if (packet.stream_index == video_stream_index) { 
     got_frame = 0; 
     ret = avcodec_decode_video2(dec_ctx, frame, &got_frame, &packet); 
     // This is old ffmpeg decode/encode API, will be deprecated later, but still working now. 
     if (got_frame) { 
      // encode frame here 
     } 
    } 
}