我正在尝试将音频文件剪切成特定部分,考虑到要剪切的秒数以及将其扩展到多长时间。
我找到了下面的代码,但由于秒数是整数,所以它并不精确。
谁能帮我操作这段代码,让我可以将 wav 文件剪切到毫秒的精度?
(即我有一个 10 秒长的音频文件,我想将其缩短到 5.32 秒到 5.55 秒之间)
https://stackoverflow.com/a/7547123/5213329
import java.io.*;
import javax.sound.sampled.*;
class AudioFileProcessor {
public static void main(String[] args) {
copyAudio("/tmp/uke.wav", "/tmp/uke-shortened.wav", 2, 1);
}
public static void copyAudio(String sourceFileName, String destinationFileName, int startSecond, int secondsToCopy) {
AudioInputStream inputStream = null;
AudioInputStream shortenedStream = null;
try {
File file = new File(sourceFileName);
AudioFileFormat fileFormat = AudioSystem.getAudioFileFormat(file);
AudioFormat format = fileFormat.getFormat();
inputStream = AudioSystem.getAudioInputStream(file);
int bytesPerSecond = format.getFrameSize() * (int)format.getFrameRate();
inputStream.skip(startSecond * bytesPerSecond);
long framesOfAudioToCopy = secondsToCopy * (int)format.getFrameRate();
shortenedStream = new AudioInputStream(inputStream, format, framesOfAudioToCopy);
File destinationFile = new File(destinationFileName);
AudioSystem.write(shortenedStream, fileFormat.getType(), destinationFile);
} catch (Exception e) {
println(e);
} finally {
if (inputStream != null) try { inputStream.close(); } catch (Exception e) { println(e); }
if (shortenedStream != null) try { shortenedStream.close(); } catch (Exception e) { println(e); }
}
}
public static void println(Object o) {
System.out.println(o);
}
public static void print(Object o) {
System.out.print(o);
}
}