java读取本地或者网络wav音频文件的时长

网上试了好多方案,jave,jaudiotagger都是不准确或者有问题的。

最后发现了如下方案

 

本地

File source = new File("C:\\Users\\5eece771f85d4c0a8ecbf510e078f697.wav");
        Clip clip = AudioSystem.getClip();
        AudioInputStream ais = AudioSystem.getAudioInputStream(source);
        clip.open(ais);
        System.out.println(clip.getMicrosecondLength() / 1000000D + " s");

网络

Clip clip = AudioSystem.getClip();
        URL url = new URL("https://9617af9fad9749eeb8a2f2bff0c715e5.wav");
        AudioInputStream ais = AudioSystem.getAudioInputStream(url);
        clip.open(ais);
        System.out.println(clip.getMicrosecondLength() / 1000000D + " s");

后来发现linux无效,所以只好下载到本地后读取再删除

URL url = new URL("http://xxx/f520b24726a175788262c46c93.wav");

        URLConnection con = null;

        try {
            con = url.openConnection();
        } catch(IOException e) {
            e.printStackTrace();
        }

        InputStream inputStream = con.getInputStream();

        File tmp = File.createTempFile("wav", ".tmp", new File("C:\\Users\\Administrator\\Desktop\\"));

        OutputStream os = new FileOutputStream(tmp);

        int bytesRead = 0;

        byte[] buffer = new byte[8192];

        while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
            os.write(buffer, 0, bytesRead);
        }

        os.close();
        inputStream.close();

        Encoder encoder = new Encoder();
        long ls = 0;

        try {
            MultimediaInfo m = encoder.getInfo(tmp);
            ls = m.getDuration();
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println(ls / 1000d);

        if (tmp.exists() && tmp.isFile()) {
            System.out.println(tmp.delete());
        }

 

你可能感兴趣的:(java)