当时为了获取时长花费好长时间,所以现在写出这文章以免后面有遇到该问题不止如何解决花费太长时间。话不多说,上代码

需要的依赖包有

  <!-- https://mvnrepository.com/artifact/org.gagravarr/vorbis-java-core --><dependency><groupId>org.gagravarr</groupId><artifactId>vorbis-java-core</artifactId><version>0.8</version></dependency><!-- https://mvnrepository.com/artifact/com.github.dadiyang/jave --><dependency><groupId>com.github.dadiyang</groupId><artifactId>jave</artifactId><version>1.0.5</version></dependency><dependency><groupId>Concentus-1.0</groupId><artifactId>Concentus-1.0</artifactId><version>1.0</version><scope>system</scope><systemPath>${project.basedir}/src/main/resources/lib/Concentus-1.0.jar</systemPath></dependency>

依赖包下载地址:

https://download.csdn.net/download/qq_36859561/31844478

工具类如下:


import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.MultimediaInfo;
import org.concentus.OpusDecoder;
import org.gagravarr.ogg.OggFile;
import org.gagravarr.opus.OpusAudioData;
import org.gagravarr.opus.OpusFile;import java.io.*;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;/*** @author John* @deprecated  TODO(压缩解压缩实现类 、 封装zip 、 rar压缩和解压缩 、获取文件时长方法)*/
public class ZipUtils {/*** zip文件压缩** @param inputFile  待压缩文件夹/文件名* @param outputFile 生成的压缩包名字*/public static void ZipCompress(String inputFile, String outputFile) throws Exception {//创建zip输出流ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outputFile));//创建缓冲输出流BufferedOutputStream bos = new BufferedOutputStream(out);File input = new File(inputFile);compress(out, bos, input, null);bos.close();out.close();}/*** @param name 压缩文件名,可以写为null保持默认*///递归压缩public static void compress(ZipOutputStream out, BufferedOutputStream bos, File input, String name) throws IOException {if (name == null) {name = input.getName();}//如果路径为目录(文件夹)if (input.isDirectory()) {//取出文件夹中的文件(或子文件夹)File[] flist = input.listFiles();if (flist.length == 0) {//如果文件夹为空,则只需在目的地zip文件中写入一个目录进入out.putNextEntry(new ZipEntry(name + "/"));} else {//如果文件夹不为空,则递归调用compress,文件夹中的每一个文件(或文件夹)进行压缩for (int i = 0; i < flist.length; i++) {compress(out, bos, flist[i], name + "/" + flist[i].getName());}}} else {//如果不是目录(文件夹),即为文件,则先写入目录进入点,之后将文件写入zip文件中out.putNextEntry(new ZipEntry(name));FileInputStream fos = new FileInputStream(input);BufferedInputStream bis = new BufferedInputStream(fos);int len = -1;//将源文件写入到zip文件中byte[] buf = new byte[1024];while ((len = bis.read(buf)) != -1) {bos.write(buf, 0, len);}bis.close();fos.close();}}/*** zip解压** @param inputFile   待解压文件名* @param destDirPath 解压路径*/public static void ZipUncompress(String inputFile, String destDirPath) throws Exception {File srcFile = new File(inputFile);//获取当前压缩文件// 判断源文件是否存在if (!srcFile.exists()) {throw new Exception(srcFile.getPath() + "所指文件不存在");}//开始解压//构建解压输入流ZipInputStream zIn = new ZipInputStream(new FileInputStream(srcFile));ZipEntry entry = null;File file = null;while ((entry = zIn.getNextEntry()) != null) {if (!entry.isDirectory()) {file = new File(destDirPath, entry.getName());if (!file.exists()) {new File(file.getParent()).mkdirs();//创建此文件的上级目录}OutputStream out = new FileOutputStream(file);BufferedOutputStream bos = new BufferedOutputStream(out);int len = -1;byte[] buf = new byte[1024];while ((len = zIn.read(buf)) != -1) {bos.write(buf, 0, len);}// 关流顺序,先打开的后关闭bos.close();out.close();}}}/*** zip解压** @param netUrl      网络地址* @param destDirPath 解压路径*/public static List<String> unzip(String netUrl, String destDirPath) throws Exception {//开始解压URL url = new URL(netUrl);HttpURLConnection conn = (HttpURLConnection) url.openConnection();//设置超时间为3秒conn.setConnectTimeout(3 * 1000);//得到输入流InputStream inputStream = conn.getInputStream();//构建解压输入流ZipInputStream zIn = new ZipInputStream(inputStream);ZipEntry entry = null;File file = null;List<String> linkedList = new LinkedList<>();while ((entry = zIn.getNextEntry()) != null) {if (!entry.isDirectory()) {
//                String fileName = System.currentTimeMillis() + entry.getName().substring(entry.getName().lastIndexOf("."));file = new File(destDirPath, entry.getName());if (!file.exists()) {new File(file.getParent()).mkdirs();//创建此文件的上级目录}OutputStream out = new FileOutputStream(file);BufferedOutputStream bos = new BufferedOutputStream(out);int len = -1;byte[] buf = new byte[1024];while ((len = zIn.read(buf)) != -1) {bos.write(buf, 0, len);}linkedList.add(entry.getName());// 关流顺序,先打开的后关闭bos.close();out.close();}}return linkedList;}/*** 音频大小判断** @param size* @return*/public static String getFormatSize(double size) {double kiloByte = size / 1024;if (kiloByte < 1) {return size + "Byte(s)";}double megaByte = kiloByte / 1024;if (megaByte < 1) {BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));return result1.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "KB";}double gigaByte = megaByte / 1024;if (gigaByte < 1) {BigDecimal result2 = new BigDecimal(Double.toString(megaByte));return result2.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "MB";}double teraBytes = gigaByte / 1024;if (teraBytes < 1) {BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));return result3.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "GB";}BigDecimal result4 = new BigDecimal(teraBytes);return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "TB";}/*** 获取时长* @param* @return*/public static Integer getOpusDuration(String pathUrl) throws Exception {FileInputStream fs = new FileInputStream(new File(pathUrl));OggFile ogg = new OggFile(fs);OpusFile of = new OpusFile(ogg);OpusAudioData ad = null;System.out.println("rate:"+of.getInfo().getSampleRate());OpusDecoder decoder = new OpusDecoder(of.getInfo().getSampleRate(),of.getInfo().getNumChannels());byte[] data_packet = new byte[of.getInfo().getSampleRate()];int samples = 0;while ((ad = of.getNextAudioPacket()) != null) {// NOTE: samplesDecoded 是decode出来的short个数,byte需要*2int samplesDecoded = decoder.decode(ad.getData(), 0, ad.getData().length, data_packet, 0, of.getInfo().getSampleRate(),false);samples += samplesDecoded;}System.out.println("duration:"+samples / of.getInfo().getSampleRate());int duration = samples / of.getInfo().getSampleRate();return duration;}/*** 音频文件获取文件时长** @param filePath* @return*/public static Long getPcmDuration(String filePath) {File source = new File(filePath);Encoder encoder = new Encoder();MultimediaInfo m;try {m = encoder.getInfo(source);return m.getDuration() / 1000;} catch (Exception e) {System.out.println("获取音频时长有误:" + e.getMessage());}return null;}public static void main(String[] args) throws Exception {String netUrl = "http://oss-cn-shenzhen.aliyuncs.com/recording-to-text/voice/1632650448539.zip";String url = "http://oss-cn-shenzhen.aliyuncs.com/recording-to-text/voice/1632468046781.zip";
//        String unzip = unzip(url, "D:\\static");
//        System.out.println(unzip);
//        zip(netUrl,"D:\\static");String str = "1627282895824.opus";int index = str.lastIndexOf(".", str.length()-1);String substring = str.substring(index);System.out.println(substring);
//
//        String substring = str.substring(str.lastIndexOf("."));
//        System.out.println(substring);String filePaths = "D:\\resource\\file\\shareData\\1627282885343.opus";
//        String filePaths = "D:\\resource\\file\\shareData\\1627282895824.opus";
//        String filePaths = "D:\\resource\\file\\shareData\\1627282885343.opus";
//        String filePaths = "D:\\resource\\file\\shareData\\1627282905283.opus";Integer audioDuration = getOpusDuration(filePaths);System.out.println(audioDuration);
//        String filePath = "D:\\resource\\file\\shareData\\1626939090359.pcm";
//        Long duration = getDuration(filePath);
//        System.out.println(duration);
//        System.out.println("解压成功");//        List<String> asList = Arrays.asList("aaa.opus", "bbb.opus");
//        List<String> collect = asList.stream().map(e -> {
//            return e.substring(e.lastIndexOf(".", e.length() - 1));
//        }).collect(Collectors.toList());
//        String s = collect.get(0);//        System.out.println("截取的后缀名:"+s);
//        String str1 = "[{\"seq\":\"1631689896351\",\"positionType\":1},{\"seq\":\"1631690004099\",\"positionType\":2},{\"seq\":\"1631690011453\",\"positionType\":1}]";
//        List<DialogueShareDTO> dtoList = JSON.parseArray(str1, DialogueShareDTO.class);
//        List<DialogueShareDTO> dtoList1 = dtoList.stream().map(item -> {
//            DialogueShareDTO shareDTO = item;
//            return shareDTO;
//        }).collect(Collectors.toList());
//        System.out.println(dtoList1);}
}

Java 获取opus 音频文件时长相关推荐

  1. Python获取mp3音频文件时长方法汇总

    '''pymediainfo: pip3 install pymediainfo 版本:5.1.0不支持网络音频 ''' class pymediainfoTest():@classmethoddef ...

  2. php获取音频的时长,PHP编程获取音频文件时长的方法【基于getid3类】

    本文实例讲述了PHP编程获取音频文件时长的方法.分享给大家供大家参考,具体如下: 问题: 昨天在新增论坛功能的时候,移动端显示音频文件需要知道是多长的音频: 具体解决方案如下: 首先就是数据库中增加保 ...

  3. Python获取.wav音频的时长

    要求是这样的: 给你一个.wav的音频,要求获取这个音频的时长.这里需要用到两个模块,contextlib和 wave. 方法1: import contextlib import wave file ...

  4. 统计文件夹下音频文件时长

    统计音频文件时长 功能 代码 主要分析 提取文件的音频时长 读取文件夹下的所有文件的绝对路径 写这个主要是为了能更好的安排自己的学习时间,学习视频的时长很难直观的看总和时间,导致安排的时间没有很好的规 ...

  5. java 获取音频文件时长

    需要导入jar包:jave 1.0.2 jar 如果是maven项目,在pom.xml文件中添加: <dependency><groupId>it.sauronsoftware ...

  6. SpringBoot获取音频文件时长

    今天在做需求的时候遇到一个问题,就是获取上传音频文件.视频文件的播放时长.虽然时长问题可以在前段通过加载获取到.但是最后还是决定使用Java,来获取时长.百度了很多,但是发现都不完整,所以用这篇博客来 ...

  7. php 获取音视频时长,PHP 利用getid3 获取音频文件时长等数据

    1.首先,我们需要先下载一份PHP类-getid3 https://codeload.github.com/JamesHeinrich/getID3/zip/master 2.解压刚才下载好的文件,拿 ...

  8. Golang: 获取mp3歌曲文件时长

    音乐时长计算公式 音乐时长 = (音乐文件大小 - 歌曲元信息大小(ID3v1,ID3v2)) / 码率 (注意单位转换) 音乐元数据([]byte)可以从文件或网络中获取 ID3v1信息位于元数据尾 ...

  9. AAC音频文件时长计算

    https://blog.csdn.net/muclenerd/article/details/52944438

最新文章

  1. Pokémon AI,使用DALL-E生成神奇宝贝图鉴
  2. 转载 Android解决java.lang.OutOfMemoryError: bitmap size exceeds VM budget
  3. Nginx图片剪裁模块探究 http_image_filter_module
  4. angularjs 服务
  5. 化工计算机软件基础考试题,化工原理模拟试题(一)及答案.doc
  6. Kettle 简介和实例
  7. mysql 集群操作系统_mysql集群部署
  8. outlook搜索栏跑到上面去了_南昌搜索引擎seo优化
  9. 空间计量:地理加权回归模型-(GWR)-参数估计
  10. matlab 怎么打开.p文件,matlab p文件肿么打开 或者 运行
  11. new Date()时间不是当前时间问题的解决方法
  12. day42.自动关机小程序
  13. Android dex2oat命令参数解释
  14. 自己做饭吃,怎样从极耗时的买菜、择菜、洗菜、切菜、配菜中解脱出来?
  15. 封装chrome镜像
  16. java版 我的世界 win10_我的世界win10版
  17. 产品干货 | 没有产品功能,谈不上用户体验
  18. smush.it更新
  19. Mac新手必看教程 Mac系统基本设置 苹果电脑的基本操作
  20. 联通C网彩信群发的问题

热门文章

  1. 出现 java.lang.UnsupportedClassVersionError 错误的原因及解决方法
  2. win7系统64位系统怎么计算机配置,Win7系统电脑最低配置要求是什么?
  3. python 处理json数据
  4. DELL XPS 15 9570 LA-G341P DDP00/DDB00 REV 1.0(A00)笔记本点位图
  5. Win10 iTunes 固件更新位置
  6. C++常用STL库详细总结
  7. 某软件平台定制开发项目技术标书
  8. SSM前后端分离技术
  9. 归并算法(Java)
  10. 如何设置U盘存储使其存储超过4G的文件