Browse Source

增加获取视频时长

songshuai 4 years ago
parent
commit
32414c0d50

+ 11 - 1
pom.xml

@@ -139,7 +139,17 @@
 		<dependency>
 			<groupId>org.apache.poi</groupId>
 			<artifactId>poi</artifactId>
-			<version>3.13</version>
+			<version>3.16</version>
+		</dependency>
+		<dependency>
+			<groupId>org.apache.poi</groupId>
+			<artifactId>poi-ooxml</artifactId>
+			<version>3.16</version>
+		</dependency>
+		<dependency>
+			<groupId>org.apache.commons</groupId>
+			<artifactId>commons-collections4</artifactId>
+			<version>4.1</version>
 		</dependency>
 		<dependency>
 			<groupId>net.sourceforge.jexcelapi</groupId>

+ 0 - 1
src/main/java/cn/efunbox/audio/impl/AudioServiceImpl.java

@@ -332,5 +332,4 @@ public class AudioServiceImpl implements AudioService {
 
     }
 
-
 }

+ 44 - 3
src/main/java/cn/efunbox/audio/utils/ExcelUtil.java

@@ -1,13 +1,21 @@
 package cn.efunbox.audio.utils;
 
 import cn.efunbox.audio.impl.AudioServiceImpl;
+import javazoom.jl.decoder.Bitstream;
+import javazoom.jl.decoder.Header;
 import jxl.Sheet;
 import jxl.Workbook;
 import jxl.read.biff.BiffException;
 import org.apache.commons.lang3.StringUtils;
+import org.apache.poi.hssf.usermodel.HSSFWorkbook;
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 
+import java.io.BufferedInputStream;
 import java.io.File;
 import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.net.URLConnection;
 import java.sql.ResultSet;
 import java.sql.SQLException;
 import java.util.Objects;
@@ -172,7 +180,7 @@ public class ExcelUtil {
     }
 
 
-    public static void main(String[] args) {
+    //public static void main(String[] args) {
         //String pathName = "C:\\Users\\Administrator\\Desktop\\移动1.xls";
         //hyImportExcel(pathName);
         //System.out.println(AudioServiceImpl.getMicrosecondLength("https://ai-admin-audio.ai160.com/audio/001/00105001/00105001011.mp3"));
@@ -180,7 +188,7 @@ public class ExcelUtil {
 
         //String pathName = "C:\\Users\\Administrator\\Desktop\\移动1.xls";
         //generatePlayTime(pathName);
-    }
+    //}
 
     public static void generatePlayTime(String name){
 
@@ -224,7 +232,7 @@ public class ExcelUtil {
             }
         }
     }
-
+    //获取播放时长
     public static String secToTime(long time) {
         String timeStr = null;
         long hour = 0;
@@ -258,4 +266,37 @@ public class ExcelUtil {
         return retStr;
     }
 
+    /**
+     * 获取音频文件时长
+     *
+     * @param filePath wav文件路径,支持本地和网络HTTP路径
+     * @return 时长/毫秒,可 /1000D 得到秒
+     * @throws Exception
+     */
+    public static long getMicrosecondLength(String filePath) {
+
+        long countTime = 0;
+        try {
+            URL urlfile = new URL(filePath);
+            //File file = new File("C:\\music\\test2.mp3");
+            //URL urlfile = file.toURI().toURL();
+            URLConnection con = urlfile.openConnection();
+            int b = con.getContentLength();// 得到音乐文件的总长度
+            BufferedInputStream bis = new BufferedInputStream(con.getInputStream());
+            Bitstream bt = new Bitstream(bis);
+            Header h = bt.readFrame();
+            int time = (int) h.total_ms(b);
+//            System.out.println(time / 1000);
+            countTime = time/1000;
+        } catch (Exception e) {
+//            e.printStackTrace();
+            //log.error("get time is error! url : {}" ,filePath);
+        } finally {
+            return countTime;
+        }
+    }
+
+    public static void main(String[] args) {
+        System.out.println(secToTime(getMicrosecondLength("http://baidu-shadow.ai160.com/vs2m-mp4/BD024/BD02404/BD02404.mp4")));
+    }
 }

+ 123 - 0
src/main/java/cn/efunbox/audio/utils/Image2Binary.java

@@ -0,0 +1,123 @@
+package cn.efunbox.audio.utils;
+
+import java.io.ByteArrayOutputStream;
+import java.io.DataInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.net.UnknownHostException;
+
+import org.apache.commons.codec.digest.DigestUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class Image2Binary {
+    private static Logger log = LoggerFactory.getLogger(Image2Binary.class);
+
+    public static byte[] toByteArray(InputStream in) throws IOException {
+
+        ByteArrayOutputStream out=new ByteArrayOutputStream();
+        byte[] buffer=new byte[1024*4];
+        int n=0;
+        while ( (n=in.read(buffer)) !=-1) {
+            out.write(buffer,0,n);
+        }
+        return out.toByteArray();
+    }
+
+    /**
+     * 网络文件转换为byte二进制
+     * @Title: toByteArray
+     * @Description: TODO(这里用一句话描述这个方法的作用)
+     * @param @param url
+     * @param @return
+     * @param @throws IOException    设定文件
+     * @return byte[]    返回类型
+     * @throws
+     */
+    public static byte[] toByteArray(String urlStr) throws IOException {
+        URL url = new URL(urlStr);
+        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
+        DataInputStream in = new DataInputStream(conn.getInputStream());
+        ByteArrayOutputStream out=new ByteArrayOutputStream();
+        byte[] buffer=new byte[1024*4];
+        int n=0;
+        while ( (n=in.read(buffer)) !=-1) {
+            out.write(buffer,0,n);
+        }
+        return out.toByteArray();
+    }
+
+    /**
+     * @throws IOException
+     * @throws MalformedURLException
+     * 网络文件转换为本地文件
+     * @Title: toByteArray
+     * @Description: TODO(这里用一句话描述这个方法的作用)
+     * @param @param url
+     * @param @return
+     * @param @throws IOException    设定文件
+     * @return byte[]    返回类型
+     * @throws
+     */
+    public static void toBDFile(String urlStr, String bdUrl) throws IOException,UnknownHostException{
+        URL url = new URL(urlStr);
+        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
+        DataInputStream in = new DataInputStream(conn.getInputStream());
+        byte[] data=toByteArray(in);
+        in.close();
+        FileOutputStream out=new FileOutputStream(bdUrl);
+        out.write(data);
+        out.close();
+    }
+
+    /**
+     * 直接获取网络文件的md5值
+     * @param urlStr
+     * @return
+     */
+    public static String getMd5ByUrl(String urlStr){
+        String md5 = null;
+        try {
+            URL url = new URL(urlStr);
+            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
+            DataInputStream in = new DataInputStream(conn.getInputStream());
+            md5 = DigestUtils.md5Hex(in);
+        } catch (IOException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }
+        return md5;
+    }
+
+    /**
+     * 获取网络文件的输入流
+     * @param urlStr
+     * @return
+     */
+    public static InputStream getInputStreamByUrl(String urlStr){
+        DataInputStream in = null;
+        try {
+            URL url = new URL(urlStr);
+            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
+            in = new DataInputStream(conn.getInputStream());
+        } catch (IOException e) {
+            log.error("url转换输入流失败,错误信息{}",e.getMessage());
+        }
+        return in;
+    }
+
+
+    public static void main(String[] args)
+    {
+        try {
+            toBDFile("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1496324940814&di=1d70e0de447be6547c372718b9b30ff6&imgtype=0&src=http%3A%2F%2Fimage.tianjimedia.com%2FuploadImages%2F2015%2F204%2F22%2FYMG9CAUWUM15.jpg","E://a.jpg");
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+//      String a = getMd5ByUrl("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1496324940814&di=1d70e0de447be6547c372718b9b30ff6&imgtype=0&src=http%3A%2F%2Fimage.tianjimedia.com%2FuploadImages%2F2015%2F204%2F22%2FYMG9CAUWUM15.jpg");
+//      System.out.println(a);
+    }
+}

+ 89 - 7
src/main/java/cn/efunbox/audio/utils/Test.java

@@ -1,26 +1,52 @@
 package cn.efunbox.audio.utils;
 
+import javazoom.jl.decoder.Bitstream;
 import javazoom.jl.decoder.BitstreamException;
+import javazoom.jl.decoder.Header;
 import lombok.extern.slf4j.Slf4j;
+import ws.schild.jave.Encoder;
 import ws.schild.jave.MultimediaInfo;
 import ws.schild.jave.MultimediaObject;
 
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
+import java.io.*;
 import java.math.BigDecimal;
 import java.math.RoundingMode;
+import java.net.URL;
+import java.net.URLConnection;
 import java.nio.channels.FileChannel;
+import java.text.DecimalFormat;
 
 @Slf4j
 public class Test {
     public static void main(String[] args) throws IOException, BitstreamException {
 
 
-//        getFileList("H:\\7m");
+        URL urlfile;
+        URLConnection con;
+        try {
+            urlfile = new URL("http://asxx-video.ai160.com/vs2m-mp4/BD052/BD05203/BD05203.mp4");
+            con = urlfile.openConnection();
+            int b = con.getContentLength();// 得到音乐文件的总长度
+            BufferedInputStream bis = new BufferedInputStream(con.getInputStream());
+            Bitstream bt = new Bitstream(bis);
+            Header h = bt.readFrame();
+            double time = h.total_ms(b);
+            System.out.println("文件时长为" +time / (1000 * 60));
+            int fileLength = con.getContentLength();
+            if (fileLength <= 0)
+                System.out.println("无法获知文件大小");
+            // 打印信息
+            DecimalFormat df = new DecimalFormat("0.0");// 格式化小数
+            String num = df.format((float) fileLength / (1024 * 1024));
+            System.out.println("文件大小为" + num + "M");
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        //secondToTime(getMicrosecondLength("http://asxx-video.ai160.com/vs2m-mp4/BD052/BD05201/BD05201.mp4"));
 
-        File source = new File("http://baidu-yuwen-video.ai160.com/vs2m/001/00103052/00103052001/00103052001.m3u8");
+//        getFileList("H:\\7m");
+            /*
+        File source = new File("http://asxx-video.ai160.com/vs2m-mp4/BD052/BD05201/BD05201.mp4");
 
         String strFileName = source.getName();
         String readVideoTime = ReadVideoTime(source);
@@ -28,7 +54,7 @@ public class Test {
 
         log.info("title : {} ,time : {},size : {}",strFileName,readVideoTime,s);
 
-
+        */
 
 /*		URL urlfile = new URL("http://ai-admin-audio.ai160.com/audio/001/00103035/00103035019.mp3");
         URLConnection con = null;
@@ -129,4 +155,60 @@ public class Test {
         }
         return size;
     }
+
+    /**
+     * 获取音频文件时长
+     *
+     * @param filePath wav文件路径,支持本地和网络HTTP路径
+     * @return 时长/毫秒,可 /1000D 得到秒
+     * @throws Exception
+     */
+    public static long getMicrosecondLength(String filePath) {
+
+        long countTime = 0;
+        try {
+            URL urlfile = new URL(filePath);
+            //File file = new File("C:\\music\\test2.mp3");
+            //URL urlfile = file.toURI().toURL();
+            URLConnection con = urlfile.openConnection();
+            int b = con.getContentLength();// 得到音乐文件的总长度
+            BufferedInputStream bis = new BufferedInputStream(con.getInputStream());
+            Bitstream bt = new Bitstream(bis);
+            Header h = bt.readFrame();
+            int time = (int) h.total_ms(b);
+//            System.out.println(time / 1000);
+            countTime = time/1000;
+        } catch (Exception e) {
+//            e.printStackTrace();
+            log.error("get time is error! url : {}" ,filePath);
+        } finally {
+            return countTime;
+        }
+
+
+    }
+
+    /**
+     * 返回日时分秒
+     * @return
+     */
+    private static void secondToTime(long seconds) {
+        MultimediaInfo info = null;
+
+        String trackLength = "";
+
+
+        long temp=0;
+        StringBuffer sb=new StringBuffer();
+        temp = seconds/3600;
+        sb.append((temp<10)?"0"+temp+":":""+temp+":");
+
+        temp=(seconds%3600)/60;
+        sb.append((temp<10)?"0"+temp+":":""+temp+":");
+
+        temp=(seconds%3600)%60;
+        sb.append((temp<10)?"0"+temp:""+temp);
+
+        System.out.println(sb.toString());
+    }
 }

+ 119 - 0
src/main/java/cn/efunbox/audio/utils/VideoUtil.java

@@ -0,0 +1,119 @@
+package cn.efunbox.audio.utils;
+
+import it.sauronsoftware.jave.MultimediaInfo;
+import it.sauronsoftware.jave.Encoder;
+import org.apache.poi.hssf.usermodel.HSSFWorkbook;
+import org.apache.poi.ss.usermodel.*;
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Objects;
+
+public class VideoUtil {
+
+
+    public static void videoTimeLength(File file) {
+        try {
+            File tempFile = null;
+            InputStream inputStream = new FileInputStream(file);
+            Workbook wb = getWorkbook(inputStream,"百度教材接口数据0229.xlsx");
+            //解析
+            Sheet sheet = wb.getSheetAt(0);
+            int rows = sheet.getPhysicalNumberOfRows();
+            for (int i = 1; i < rows; i++) {
+                Row row = sheet.getRow(i);
+                if (!Objects.isNull(row)) {
+                    String title = getCell(row.getCell(8));
+                    String playUrl = getCell(row.getCell(11));
+                    String trackLength = "";
+                    tempFile = getFileByUrl(playUrl);
+                    MultimediaInfo mInfo = new Encoder().getInfo(tempFile);
+                    long length = mInfo.getDuration();
+                    int h = (int)(length/3600000);
+                    long hr = length%3600000;
+                    long m = ((hr)/60000);
+                    long mr = length%60000;
+                    int s = (int)mr/1000;
+                    if(h<10){
+                        trackLength+="0"+h;
+                    }else{
+                        trackLength +=h;
+                    }
+                    trackLength += ":";
+                    if(m<10){
+                        trackLength+="0"+m;
+                    }else {
+                        trackLength += m;
+                    }
+                    trackLength += ":";
+                    if(s<10){
+                        trackLength+="0"+s;
+                    }else {
+                        trackLength += s;
+                    }
+                    System.out.println(title+"================"+trackLength);
+                    row.getCell(12).setCellValue(trackLength);
+                }
+
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+    /**
+     * 获取工作簿对象
+     * @param inStr
+     * @param fileName
+     * @return
+     * @throws Exception
+     */
+    private static Workbook getWorkbook(InputStream inStr, String fileName) throws Exception {
+        Workbook wb = null;
+        String fileType = fileName.substring(fileName.lastIndexOf(".") + 1 );
+        if ("xls".equals(fileType)) {
+            wb = new HSSFWorkbook(inStr);  //2003-
+        } else if ("xlsx".equals(fileType)) {
+            wb = new XSSFWorkbook(inStr);  //2007+
+        } else {
+            throw new Exception("解析的文件格式有误!");
+        }
+        return wb;
+    }
+
+    private static String getCell(Cell cell) {
+        if (Objects.nonNull(cell)) {
+            CellType cellType = cell.getCellTypeEnum();
+            if (cellType == CellType.STRING) {//字符串类型
+                //System.out.println(cell.getStringCellValue());
+                return cell.getStringCellValue().trim();
+            }
+            if (cellType == CellType.NUMERIC) {//数字类型
+                int numericCellValue = (int) cell.getNumericCellValue();
+                //System.out.println(numericCellValue);
+                return numericCellValue + "";
+            }
+        }
+        return null;
+    }
+
+    /**
+     * 获取网络文件,暂存为临时文件
+     * @param url
+     * @return
+     * @throws IOException
+     */
+    public static File getFileByUrl(String url) throws IOException {
+        File tmpFile = File.createTempFile("temp", ".tmp");//创建临时文件
+        Image2Binary.toBDFile(url, tmpFile.getCanonicalPath());
+        return tmpFile;
+    }
+
+    public static void main(String[] args) {
+        File file = new File("C:\\Users\\Administrator\\Desktop\\百度教材接口数据0229.xlsx");
+        videoTimeLength(file);
+    }
+}