Série d'images FFmpeg: obtenir la durée de la vidéo
1. Scénario commercial
Exigence commerciale: affichez la durée de la vidéo mise en ligne.
2. Cadre FFmpeg pour traiter les informations vidéo
Site officiel de FFmpeg: http://ffmpeg.org/
3. Mise en œuvre du code
3.1 Windows installe FFmpeg
Je vais vous apprendre dans ce code JAVA de cinq minutes: Démo vidéo d'implémentation FFmpeg (version fenêtre) écrite de manière très détaillée, installez FFmepg sur windows / Linux, je ne vais pas développer ici.
3.2 Exécuter le mot de passe pour afficher les informations vidéo
Après avoir installé FFmpeg dans la fenêtre, exécutez la commande pour obtenir la durée en cmd:
F:\ffmpegDemo\ffmpeg\bin\ffmpeg.exe -i F://ffmpegDemo//test.mp4
PS: Décompressez le programme ffmpeg F: \ ffmpegDemo \ ffmpeg \ bin \ ffmpeg.exe et la vidéo locale stockée dans les fenêtres: F: //ffmpegDemo//test.mp4
L'effet de mise en œuvre est le suivant:
3.3 Java analyse les informations et renvoie la durée
Exécutez la ligne de commande via FFmpeg pour obtenir les informations vidéo renvoyées, filtrez les données cibles des informations vidéo via java et renvoyez-les.
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. Publier la démo terminée
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 "";
}
}
L'effet de mise en œuvre est le suivant:
Fichier source vidéo: