wav音频的剪切

wav格式音频剪切功能的完美实现方案。



import java.io.*;
import javax.sound.sampled.*;

public class AudioFileProcessor {



    /**
     *
     * @param sourceFileName 源文件路径
     * @param destinationFileName 生成文件路径
     * @param start 切割开始时间(毫秒)
     * @param end 切割结束时间(毫秒)
     */
    public static void CutAudio(String sourceFileName, String destinationFileName, int start, int end) {
        AudioInputStream inputStream = null;
        AudioInputStream shortenedStream = null;
        try {
            File file = new File(sourceFileName);
            //获取指定的音频文件格式 File
            AudioFileFormat fileFormat = AudioSystem.getAudioFileFormat(file);
            //获取包含在音频文件中的音频数据的格式
            AudioFormat format = fileFormat.getFormat();
            //从提供的输入流中获取音频输入流
            inputStream = AudioSystem.getAudioInputStream(file);
            float bytesPerSecond = format.getFrameSize() *  format.getFrameRate()/1000;
            //跳过并丢弃该音频输入流中指定数量的字节。
            inputStream.skip((long)(start * bytesPerSecond));
            long framesOfAudioToCopy =(long)( (end-start) *  format.getFrameRate()/1000);
            shortenedStream = new AudioInputStream(inputStream, format, framesOfAudioToCopy);
            File destinationFile = new File(destinationFileName);
            AudioSystem.write(shortenedStream, fileFormat.getType(), destinationFile);
        } catch (Exception e) {
            System.out.println(e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Exception e) {
                    System.out.println(e);
                }
            }

            if (shortenedStream != null)
            {
                try {
                    shortenedStream.close();
                } catch (Exception e) {
                    System.out.println(e);
                }
            }
        }
    }

   
}

posted @ 2019-09-01 22:11  zofun  阅读(1478)  评论(0编辑  收藏  举报