切割波形文件
问题内容:
如何.wave
使用Java 剪切文件?
我想要的是:
当用户按下标cut
有按钮的按钮时,应将音频从前一个mark
(以纳秒为单位)剪切到当前位置(以纳秒为单位)。
(在剪切声音后,标记被定位到当前位置(以纳秒为单位)) 当我获得一段音频后,我想保存该段音频文件。
// obtain an audio stream
long mark = 0; // initially set to zero
//get the current position in nanoseconds
// after that how to proceed ?
// another method ?
我怎样才能做到这一点 ?
问题答案:
最初由Martin Dow回答
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); }
}
}
}