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

   
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM