Java 获取opus 音频文件时长

13 篇文章 0 订阅

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

需要的依赖包有 

  <!-- 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);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Java中解码opus文件,您可以使用JOpus库。JOpus是一个Java库,用于解码和编码Opus音频格式。 以下是使用JOpus库解码Opus文件的示例代码: ```java import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.SourceDataLine; import javax.sound.sampled.DataLine.Info; import com.sun.media.sound.WaveFileReader; import com.sun.media.sound.WaveFileWriter; import org.concentus.OpusDecoder; import java.io.*; public class OpusDecoderExample { public static void main(String[] args) throws Exception { // Load Opus file File inputFile = new File("input.opus"); // Create Opus decoder OpusDecoder decoder = new OpusDecoder(48000, 1); // Create output file File outputFile = new File("output.wav"); // Open input stream InputStream inputStream = new FileInputStream(inputFile); // Open output stream OutputStream outputStream = new FileOutputStream(outputFile); // Decode Opus file byte[] opusData = new byte[1024]; byte[] pcmData = new byte[1024]; int bytesRead = 0; while ((bytesRead = inputStream.read(opusData)) >= 0) { int frameSize = decoder.decode(opusData, 0, bytesRead, pcmData, 0, 1024); outputStream.write(pcmData, 0, frameSize); } // Close streams inputStream.close(); outputStream.close(); // Print output file information WaveFileReader waveFileReader = new WaveFileReader(); AudioInputStream audioInputStream = waveFileReader.getAudioInputStream(outputFile); AudioFormat audioFormat = audioInputStream.getFormat(); System.out.println("Output file format: " + audioFormat); System.out.println("Output file length: " + outputFile.length()); } } ``` 在此示例中,我们加载Opus文件,创建一个Opus解码器并将PCM数据写入WAV文件中。在解码过程中,我们使用了JOpus库提供的OpusDecoder类来解码Opus文件。我们还使用Java标准库中的IO类来读取和写入文件。最后,我们使用Java标准库中的javax.sound.sampled类来获取解码后的PCM音频格式和输出文件的长度。 请注意,这个示例代码中使用的com.sun.media.sound包是Oracle官方的包,但它不是标准Java API的一部分,这意味着在某些情况下可能无法使用。如果您遇到了这样的问题,您可以尝试使用开源的替代品,如JavaSound或JavaFX。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值