切割波形文件
如何使用java剪切.wave
文件?
我想要的是:
当用户按下标记为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); } } }
}
最初在这里回答
- 从文件源创建一个AudioInputStream (您可以使用
AudioSystem.getAudioInputStream(File)
)。 - 使用流的
getFormat()
AudioFormat来确定需要从流和位置读取的字节数。- 文件位置(字节)=时间(秒)/采样率*样本大小(位)* 8 *波形文件的通道
- 基于仅从原始文件中读取所需数据的原始文件创建新的AudioInputStream。 您可以通过跳过原始流中所需的字节,创建一个修复端点长度的包装器,然后使用AudioSystem.getAudioInputStream(AudioFormat,AudioInputStream)来完成此操作。 还有其他方法可以做到这一点,这可能会更好。
- 使用AudioSystem.write()方法写出新文件。
您可能还想查看Tritonus及其AudioOutputStream,它可能会让事情变得更容易。
有一个API可以帮助您实现目标http://code.google.com/p/musicg-sound-api/