Java获取视频时长和封面截图
Java视频时长的计算以及视频封面图截取
本人使用的maven进行下载对应的jar包,其中代码适用window环境和linux环境,亲自测过,没问题。


maven需要用到的groupId和artifactId以及版本,如下所示:
<dependency>
<groupId>org.bytedeco</groupId>
<artifactId>javacv</artifactId>
<version>1.4.1</version>
</dependency>
<dependency>
<groupId>org.bytedeco</groupId>
<artifactId>javacpp</artifactId>
<version>1.4.1</version>
</dependency>
<dependency>
<groupId>org.bytedeco.javacpp-presets</groupId>
<artifactId>opencv-platform</artifactId>
<version>3.4.1-1.4.1</version>
</dependency>
<dependency>
<groupId>org.bytedeco.javacpp-presets</groupId>
<artifactId>ffmpeg-platform</artifactId>
<version>3.4.2-1.4.1</version>
</dependency>
java代码
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;
/**
* 视频工具
* @author
*
*/
public class VideoUtil {
/**
* 获取指定视频的帧并保存为图片至指定目录
* @param file 源视频文件
* @param framefile 截取帧的图片存放路径
* @throws Exception
*/
public static void fetchPic(File file, String framefile) throws Exception{
FFmpegFrameGrabber ff = new FFmpegFrameGrabber(file);
ff.start();
int lenght = ff.getLengthInFrames();
File targetFiwww.devze.comle = new File(framefile);
int i = 0;
Frame frame = null;
while (i < lenght) {
// 过滤前5帧,避免出现全黑的图片,依自己情况而定
frame = ff.grabFrame();
if ((i > 5) && (frame.image != null)) {
break;
}
i++;
}
String imgSuffix = "jpg";
if(framefile.indexOf('.') != -1){
String[] arr = framefile.split("\\.");
if(arr.length>=2){
imgSuffix = arr[1];
}
}
Java2DFrameConverter converter =new Java2DFrameConverter();
BufferedImage srcBi =converter.getBufferedImage(frame);
int owidth = srcBi.getWidth();
int oheight = srcBi.getHeight();
// 对截取的帧进行等比例缩放
int width = 800;
int height = (int) (((double) width / owidth) * oheight);
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
bi.getGraphics().drawImage(srcBi.getScaledInstance(width, height, Image.SCALE_SMOOTH),0, 0, null);
try {
ImageIO.write(bi, imgSuffix, targetFile);
}catch (Exception e) {
e.printStackTrace();
}
ff.stop();
}
/**
* 获取视频时长,单位为秒
* @param file
* @return 时长(s)
*/
public static Long getVideoTime(File file){
Long times = 0L;
try {
FFmpegFrameGrabber ff = new FFmpegFrameGrabber(file);
ff.start();
times = ff.getLengthInTime()/(1000*1000);
ff.stop();
} catch (Exception e) {
e.printStackTrace();
}
return times;
}
}
以上就是java获取视频的时长,以及视频获取其中封面截图。
除了上文的方法,小编还为大家整理了其他java获取视频时长(实测可行)的方法,希望对大家有所帮助
下面是完整代码
pom.XML
<!-- mp3文件支持(如语音时长)-->
<dependency>
<groupId>org</groupId>
<artifactId>jaudiotagger</artifactId>
<version>2.0.1</version>
</dependency>
<!-- mp4文件支持(如语音时长)-->
<dependency>
<groupId>com.googlecode.mp4parser</groupId>
<artifactId>isoparser</artifactId>
<version>1.1.22</version>
</dependency>
单元测试
package com.opensourceteams.modules.java.util.video;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.*;
public class VideoUtilTest {
@Test
public void getDuration() throws IOException {
String path = "/Users/liuwen/Downloads/temp/语音测试文件/xiaoshizi.mp3" ;
/*path 为本地地址 */
long result = VideoUtil.getDuration(path);
System.out.println(result);
}
}
工具类
package com.opensourceteams.modules.java.util.video;
import com.coremedia.iso.IsoFile;
import java.io.IOException;
public class VideoUtil {
/**
* 获取视频文件的播放长度(mp4、mov格式)
* @param videoPath
* @return 单位为毫秒
*/
public static long getMp4Duration(String videoPath) throws IOException {
IsoFile isoFile = new IsoFile(videoPath);
long lengthInSeconds =
isoFile.getMovieBox().getMovieHeaderBox().getDuration() /
isoFile.getMoviepythonBox().getMovieHeaderBox().getTimescale();
return lengthInSeconds;
}
/**
* 得到语音或视频文件时长,单位秒
* @param filePath
* @return
* @throws IOException
*/
public static long getDuration(String filePath) throws IOException {
String format = getVideoFormat(filePath);
long result = 0;
if("wav".equals(format)){
result = AudioUtil.getDuration(filePath).intValue();
}else if("mp3".equals(format)){
result = AudioUtil.getMp3Duration(filePath).intValue();
}else if("m4a".equals(format)) {
result = VideoUtil.getMp4Duration(filePath);
}else if("mov".equals(format)){
result = VideoUtil.getMp4Duration(filePath);
}else if("mp4".equals(format)){
result = VideoUtil.getMp4Duration(filePath);
}
return result;
}
/**
* 得到语音或视频文件时长,单位秒
* @param filePath
* @return
* @throws IOException
*/
public static long getDuration(String filePath,String format) throws IOException {
long result = 0;
if("wav".equals(format)){
js result = AudioUtil.getDuration(filePath).intValue();
}else if("mp3".equals(format)){
result = AudioUtil.getMp3Duration(filePath).intValue();
}else if("m4a".equals(format)) {
result = VideoUtil.getMp4Duration(filePath);
}else if("mov".equals(format)){
result = VideoUtil.getMp4Duration(filePath);
}else if("mp4".equals(format)){
result = VideoUtil.getMp4Duration(filePath);
}
return result;
}
/**
* 得到文件格式
* @param path
* @return
*/
public static String getVideoFormat(String path){
return path.toLowerCase().substring(path.toLowerCase().lastIndexOf(".") + 1);
}
}
package com.opensourceteams.modules.java.util.video;
import org.jaudiotagger.audio.AudioFileIO;
import org.jaudiotagger.audio.mp3.MP3AudioHeader;
import org.jaudiotagger.audio.mp3.MP3File;
import javax.soundjs.sampled.AudioFormat;
import javahttp://www.devze.comx.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudIOSystem;
import java.io.File;
public class AudioUtil {
/**
* 获取语音文件播放时长(秒) 支持wav 格式
* @param filePath
* @return
*/
public static Float getDuration(String filePath){
try{
File destFile = new File(filePath);
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(destFile);
AudioFormat format = audioInputStream.getFormat();
long audioFileLength = destFile.length();
int frameSize = format.getFrameSize();
float frameRate = format.getFrameRate();
float durationInSeconds = (audioFileLength / (frameSize * frameRate));
return durationInSeconds;
}catch (Exception e){
e.printStackTrace();
return 0f;
}
}
/**
* 获取mp3语音文件播放时长(秒) mp3
* @param filePath
* @return
*/
public static Float getMp3Duration(String filePath){
try {
File mp3File = new File(filePath);
MP3File f = (MP3File) AudioFileIO.read(mp3File);
MP3AudioHeader audioHeader = (MP3AudioHeader)f.getAudioHeader();
return Float.parseFloat(audioHeader.getTrackLength()+"");
} catch(Exception e) {
e.printStackTrace();
return 0f;
}
}
/**
* 获取mp3语音文件播放时长(秒)
* @param mp3File
* @return
*/
public static Float getMp3Duration(File mp3File){
try {
//File mp3File = new File(filePath);
MP3File f = (MP3File) AudioFileIO.read(mp3File);
MP3AudioHeader audioHeader = (MP3AudioHeader)f.getAudioHeader();
return Float.parseFloat(audioHeader.getTrackLength()+"");
} catch(Exception e) {
e.printStackTrace();
return 0f;
}
}
/**
* 得到pcm文件的毫秒数
*
* pcm文件音频时长计算
* 同图像bmp文件一样,pcm文件保存的是未压缩的音频信息。 16bits 编码是指,每次采样的音频信息用2个字节保存。可以对比下bmp文件用分别用2个字节保存RGB颜色的信息。 16000采样率 是指 1秒钟采样 16000次。常见的音频是44100HZ,即一秒采样44100次。 单声道: 只有一个声道。
*
* 根据这些信息,我们可以计算: 1秒的16000采样率音频文件大小是 2*16000 = 32000字节 ,约为32K 1秒的8000采样率音频文件大小是 2*8000 = 16000字节 ,约为 16K
*
* 如果已知录音时长,可以根据文件的大小计算采样率是否正常。
* @param filePath
* @return
*/
public static long getPCMDurationMilliSecond(String filePath) {
File file = new File(filePath);
//得到多少秒
long second = file.length() / 32000 ;
long milliSecond = Math.round((file.length() % 32000) / 32000.0 * 1000 ) ;
return second * 1000 + milliSecond;
}
}
因为我们是根据在线url获取视频时长的
还需要再添加一步: 本地临时存储文件
public void getDuration() throws IOException {
File file = getFileByUrl("https://video-ecook.oss-cn-hangzhou.aliyuncs.com/76bd353630be47f0b5447ec06201ee56.mp4");
String path = file.getCanonicalPath(); ;
System.out.println(path);
long result = VideoUtil.getDuration(path);
System.out.println(result + "s");
}
public static File getFileByUrl(String url) throws IOException {
File tmpFile = File.createTempFile("temp", ".mp4");//创建临时文件
Image2Binary.toBDFile(url, tmpFile.getCanonicalPath());
return tmpFile;
}
到此这篇关于Java获取视频时长和封面截图的文章就介绍到这了,更多相关Java获取视频时长和封面内容请搜索编程客栈(www.devze.com)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程客栈(www.devze.com)!
加载中,请稍侯......
精彩评论