2011-09-18 107 views
3

如何使用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 ? 

我该怎么做?

+4

仅供参考,大多数回答。 wav文件是44.1KHz,意味着每个样本持续超过2000ns。你不会得到毫微秒的精度 –

+1

你已经做了什么来解决这个问题?你在寻找现有解决方案时做了哪些研究? – Asaf

+2

@阿萨夫可能你没有读过这个问题。你只能阅读标题! –

回答

4

这最初是由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); } 
} 
} 

}

最初回答HERE

0
  • 从文件源创建一个AudioInputStream(对此可以使用AudioSystem.getAudioInputStream(File))。
  • 使用流的getFormat()中的AudioFormat来确定需要从流中读取的字节数和位置。
    • 文件位置(字节)=时间(秒)/采样率*样品大小(比特)* 8 *为波形文件通道
  • 创建基于原始新的AudioInputStream仅读取数据你想从原来的。您可以通过跳过原始流中需要的字节来实现此目的,创建一个封装器来修复端点的长度,然后使用AudioSystem.getAudioInputStream(AudioFormat,AudioInputStream)。还有其他方法可以做得更好。
  • 使用AudioSystem.write()方法写出新文件。

您可能还想看看Tritonus及其AudioOutputStream,它可能会使事情变得更容易。