>我正在尝试将音频文件剪切成特定部分,给定要剪切的秒数和将其延长多长时间。
我找到了下面的代码,但由于秒是作为 int 给出的,所以它并不精确。
谁能帮作这段代码,让我将 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);
}
}
wav 的格式通常为每秒 44100 帧。立体声、16 位编码(CD 质量)每秒提供 4 * 44100 字节,或每秒 176,400 字节。一帧只消耗 1/44100 秒,或 .02 毫秒(如果我的数学是正确的),所以使用毫秒的分数秒应该不是问题。
只需使您的输入浮动或双倍而不是整数。
在使用 startSecond 或 secondsToCopy 进行倍数的地方,您很可能需要将答案四舍五入为 4 的倍数(或任何每帧量的字节数)才能引用帧边界。