当时为了获取时长花费好长时间,所以现在写出这文章以免后面有遇到该问题不止如何解决花费太长时间。话不多说,上代码
需要的依赖包有
<!-- 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需要*2
int 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);
}
}