FFmpegフレームシリーズ:ビデオの長さを取得する
1.ビジネスシナリオ
ビジネス要件:アップロードされた動画の長さを表示します。
2.ビデオ情報を処理するためのFFmpegフレームワーク
FFmpeg公式ウェブサイト:http : //ffmpeg.org/
3.コードの実装
3.1 WindowsインストールFFmpeg
この5分のJAVAコードで教えます。FFmpeg 実装のビデオデモ(ウィンドウバージョン)は非常に詳細に記述されています。Windows/ LinuxにFFmepgをインストールします。ここでは詳しく説明しません。
3.2ビデオ情報を表示するためのパスワードの実行
ウィンドウにFFmpegをインストールした後、コマンドを実行してcmdで期間を取得します。
F:\ffmpegDemo\ffmpeg\bin\ffmpeg.exe -i F://ffmpegDemo//test.mp4
PS:ffmpegプログラムF:\ ffmpegDemo \ ffmpeg \ bin \ ffmpeg.exeおよびウィンドウに保存されているローカルビデオを解凍します:F://ffmpegDemo//test.mp4
実装効果は次のとおりです。
3.3 Javaは情報を解析し、期間を返します
FFmpegを介してコマンドラインを実行し、返されたビデオ情報を取得し、Javaを介してビデオ情報のターゲットデータをフィルター処理して返します。
public static void main(String[] args) {
String timeLength = getVideoTime("F://ffmpegDemo//test.mp4","F:\\ffmpegDemo\\ffmpeg\\bin\\ffmpeg.exe");
if(timeLength.length()>0){
//字符串截取
timeLength =timeLength.substring(0,timeLength.indexOf("."));
}
System.out.println("视频时长:"+timeLength);
}
4.完成したデモを投稿する
public class ExecWindowCMD {
public static void main(String[] args) {
String timeLength = getVideoTime("F://ffmpegDemo//test.mp4","F:\\ffmpegDemo\\ffmpeg\\bin\\ffmpeg.exe");
if(timeLength.length()>0){
//字符串截取
timeLength =timeLength.substring(0,timeLength.indexOf("."));
}
System.out.println("视频时长:"+timeLength);
}
/**
*获取视频时间
* @param video_path 视频路径
* @param ffmpeg_path ffmpeg安装路径
* @return
*/
public static String getVideoTime(String video_path, String ffmpeg_path) {
List<String> commands = new java.util.ArrayList<String>();
commands.add(ffmpeg_path);
commands.add("-i");
commands.add(video_path);
System.out.println("命令行:"+ffmpeg_path+" -i "+video_path);
try {
ProcessBuilder builder = new ProcessBuilder();
builder.command(commands);
final Process p = builder.start();
//从输入流中读取视频信息
BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream()));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
//从视频信息中解析时长
String regexDuration = "Duration: (.*?), start: (.*?), bitrate: (\\d*) kb\\/s";
Pattern pattern = Pattern.compile(regexDuration);
Matcher m = pattern.matcher(sb.toString());
if (m.find()) {
//System.out.println(video_path+",视频时长:"+m.group(1)+", 开始时间:"+m.group(2)+",比特率:"+m.group(3)+"kb/s");
return m.group(1);
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
}
実装効果は次のとおりです。
ビデオソースファイル: