Thursday, May 5, 2016

FFmpeg: Concatenate videos

Introduction

FFmpeg连接(组合、合并)多视频文件的操作。
文献[1]示例代码:
1
2
3
4
ffmpeg -i input1.avi -qscale:v 1 intermediate1.mpg
ffmpeg -i input2.avi -qscale:v 1 intermediate2.mpg
ffmpeg -i concat:"intermediate1.mpg|intermediate2.mpg" -c copy intermediate_all.mpg
ffmpeg -i intermediate_all.mpg -qscale:v 2 output.avi
简述以上处理过程:文件input1.avi和input2.avi先经格式转换至mpg文件,随后这两个mpg文件首尾连接输出一个合并文件,最后将这一合并文件再经格式转换至.avi格式文件。

Example

在Matlab启动FFmpeg实现如上同样的处理流程,代码:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
% Created by LI Xu
% Version 1.0
% April 20, 2016

% Description:
% Combine several videos to one

% If you have any question about this code,
% please do not hesitate to contact me via E-mail: 
% jeremy456@163.com

% Blog:
% http://blog.sciencenet.cn/u/lixujeremy
% http://lixuworld.blogspot.com/

clear
clc

% Source Directory
SouDir='input';
% Destination Directory
DesDir='output';
otpath=fullfile(DesDir, 'all.wmv');
% All Input Videos
videos=dir(fullfile(SouDir, '*.wmv'));

% Loop to convert input videos
% to the mpg format

disp('...Start to convert to mpg format...');
for ii=1:length(videos)
    vidname=videos(ii).name;
    [~, filename, ~]=fileparts(vidname);
    vidpath=fullfile(SouDir, vidname);
    % Mpg
    mpgpath=fullfile(SouDir, [filename, '.mpg']);
    ConToMpg(vidpath, mpgpath); 
end
disp('...Finish to convert to mpg format...');

% All mpg Videos
mpgfiles=dir(fullfile(SouDir, '*.mpg'));
% Construct file path string
vidstr=[];
for ii=1:length(mpgfiles)
    mpgname=mpgfiles(ii).name;
    mpgpath=fullfile(SouDir, mpgname);
    if isempty(vidstr)
        vidstr=mpgpath;
    else
        vidstr=[vidstr, '|', mpgpath];
    end
end


disp('...Start to Concatenate...');
% Command
outmpg='temporary.mpg';
cmdstr=['ffmpeg -i concat:"', vidstr, '"'];
cmdstr=[cmdstr, ' -c copy ', outmpg];
[stuat, cmdout]=system(cmdstr);

% Delete all mpg files
DeleteMPG(SouDir, mpgfiles);

% Convert to wmv
ConToWMV(outmpg, otpath);
delete(outmpg);
disp('...Finish to Concatenate...');
disp('Exit');
disp('**************************************************');
注意:合并文件比之输入文件大小之和还大出许多。

References

No comments:

Post a Comment