簡體   English   中英

將FileInputStream的一部分寫入FileOutPutstream

[英]Write part of FileInputStream into FileOutPutstream

我試圖獲取一個已錄制的.wav文件,然后創建一個包含該wav文件的新輸出流。 最終目標是讓我拍波形,在特定點將其分割,然后在中間插入新音頻。

我當時使用FFMPEG來執行此操作,但是FFMPEG的性能在最新版本的Android上已經變得非常糟糕。

我認為我最大的問題是缺乏對.read()和.write()方法的完全了解。

這是我嘗試過的

final int SAMPLE_RATE = 44100; // Hz
final int ENCODING = AudioFormat.ENCODING_PCM_16BIT;
final int CHANNEL_MASK = AudioFormat.CHANNEL_IN_MONO;

in1 = new FileInputStream(Environment.getExternalStorageDirectory() + "/recording.wav");

out = new FileOutputStream(Environment.getExternalStorageDirectory() + "/recording_part_1.wav");    

// Write out the wav file header
wavHeader.writeWavHeader(out, CHANNEL_MASK, SAMPLE_RATE, ENCODING);

while (in1.read(buffer, 0, buffer.length) != -1) {
           out.write(buffer);
}

out.close();
in1.close();

File fileToSave = new File(Environment.getExternalStorageDirectory() + "/GMT/recording_part_1.wav");

try {
    // This is not put in the try/catch/finally above since it needs to run
    // after we close the FileOutputStream
    wavHeader.updateWavHeader(fileToSave);
} catch (IOException ex) {

}

上面的作品,但它只是復制整個事情。 記錄代碼writeWaveHeader和updateWavHeader都來自這個要點https://gist.github.com/kmark/d8b1b01fb0d2febf5770

我已經嘗試過類似的東西

for (int i = 0; i < in1.getChannel().size() / 2; i++) {
            out.write(in1.read(buffer, i, 1));
}

但這根本不起作用。 我也想

            byte[] byteInput = new byte[(int)in1.getChannel().size() - 44];
        while (in1.read(byteInput, 44, byteInput.length - 45) != -1) {
            out.write(byteInput, 44, byteInput.length /2);
        }

希望這只會創建一個包含一半文件的新文件。 我一直在看文檔,但是做錯了。

看看FileInputStream的文檔

您的方法還不錯。 這可以完成一些工作:

for (int i = 0; i < in1.getChannel().size() / 2; i++) {
    out.write(in1.read(buffer, i, 1));
}

醫生說:

read(byte [] b,int off,int len) 從此輸入流中最多將len個字節的數據讀取到一個字節數組中。

您將緩沖區作為正確的byte []傳遞。

然后,您將i作為偏移量傳遞。 您的偏移量應為0 (因此從音頻文件開始)。

對於len,您需要通過1。這應該是您要復制的長度。 因此,在那里傳遞in1.getChannel()。size()/ 2 (直到音頻文件的中間)。

在這種情況下,您甚至不需要循環,因為read方法可以為您做所有事情。 要編輯零件的開始和結束,您需要更改2.&3。 參數。

因此,這應該為您工作:

 byte[] buffer = new byte[(int)(in1.gerChannel().size() / 2)];
 in1.read(buffer, 0, (int)(in1.gerChannel().size() / 2));
 out.write(buffer);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM