我正在尝试将一个音频文件剪切成特定的部分,给出第二个要剪切的位置和扩展到的长度。
我找到了下面的代码,但由于秒是以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);
}
}发布于 2016-05-25 05:53:18
wav的格式通常是每秒44100帧。立体声,16位编码(CD质量)提供4* 44100字节/秒,或176,400字节/秒。一帧只消耗1/44100秒,或.02毫秒(如果我的计算正确的话),所以使用毫秒的分数应该不是问题。
只需将输入设为浮点型或双精度型,而不是整型。
在使用startSecond或secondsToCopy进行乘法运算的地方,为了引用帧边界,很可能需要将答案四舍五入为4的倍数(或每帧字节数多少)。
https://stackoverflow.com/questions/37400771
复制相似问题