2011-09-18 114 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,它可能會使事情變得更容易。